import { Command, CommandRunner, Option } from 'nest-commander';
import { Injectable, Logger } from '@nestjs/common';
import { JsonImportService } from 'modules/feature/can/populate-db-json/json-populate.service';
import * as fs from 'fs';
import * as path from 'path';
import { DataSource } from 'typeorm';

interface JsonImportCommandOptions {
  directory: string;
  pattern?: string;
  batchSize?: number;
  source?: string;
  verbose?: boolean;
}

@Injectable()
@Command({ name: 'import-json', description: 'Import JSON files containing hospital patient data with contacts' })
export class JsonImportCommand extends CommandRunner {
  private readonly logger = new Logger(JsonImportCommand.name);

  constructor(
    private readonly jsonImportService: JsonImportService,
    private readonly dataSource: DataSource,
  ) {
    super();
  }

  async run(passedParams: string[], options?: JsonImportCommandOptions): Promise<void> {
    try {
      // Initialize database connection
      if (!this.dataSource.isInitialized) {
        await this.dataSource.initialize();
        this.logger.log('Database connection established');
      }

      if (!options?.directory) {
        this.logger.error('Directory path is required');
        return;
      }

      // Verify directory exists
      const directoryPath = path.resolve(options.directory);
      if (!fs.existsSync(directoryPath)) {
        this.logger.error(`Directory not found: ${directoryPath}`);
        return;
      }

      this.logger.log(`Processing JSON files from directory: ${directoryPath}`);

      const batchSize = options?.batchSize || 1000;
      const pattern = options?.pattern || '**/*.json';
      const source = options?.source || 'Hospital Records';

      this.logger.log(`Using pattern: ${pattern}, batch size: ${batchSize}, source: ${source}`);

      await this.jsonImportService.importJsonData(directoryPath, pattern, batchSize, source);

      this.logger.log('JSON import completed successfully');
    } catch (error) {
      this.logger.error('Import failed: ' + error.message);
      process.exit(1);
    } finally {
      if (this.dataSource.isInitialized) {
        await this.dataSource.destroy();
      }
    }
  }

  @Option({
    flags: '-d, --directory <directory>',
    description: 'Directory containing JSON files to import (required)',
  })
  parseDirectory(val: string): string {
    return val;
  }

  @Option({
    flags: '-p, --pattern [pattern]',
    description: 'Glob pattern for JSON files (e.g., "**/*.json")',
    defaultValue: '**/*.json',
  })
  parsePattern(val: string): string {
    return val;
  }

  @Option({
    flags: '-b, --batch-size [batchSize]',
    description: 'Number of files to process in a single batch',
    defaultValue: '1000',
  })
  parseBatchSize(val: string): number {
    return parseInt(val, 10);
  }

  @Option({
    flags: '-s, --source [source]',
    description: 'Source name for the contact data',
    defaultValue: 'Hospital Records',
  })
  parseSource(val: string): string {
    return val;
  }

  @Option({
    flags: '-v, --verbose',
    description: 'Enable verbose logging',
  })
  parseVerbose(): boolean {
    return true;
  }
}

/**
 * # Import all JSON files from the hospital directory
npm run import-json -- --directory path/to/jsonfile
 */
