import { NestFactory } from '@nestjs/core';
import { AppModule } from '../app.module';
import { S3StorageAdapter } from '@infrastructure/storage/s3-storage.adapter';
import { TypeOrmCsvRateConfigRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-csv-rate-config.repository';
import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';

/**
 * Script to migrate existing CSV files to MinIO
 * Usage: npm run ts-node src/scripts/migrate-csv-to-minio.ts
 */
async function migrateCsvFilesToMinio() {
  const app = await NestFactory.createApplicationContext(AppModule);
  const s3Storage = app.get(S3StorageAdapter);
  const csvConfigRepository = app.get(TypeOrmCsvRateConfigRepository);
  const configService = app.get(ConfigService);

  try {
    console.log('🚀 Starting CSV migration to MinIO...\n');

    const bucket = configService.get<string>('AWS_S3_BUCKET', 'xpeditis-csv-rates');
    const csvDirectory = path.join(
      process.cwd(),
      'src',
      'infrastructure',
      'storage',
      'csv-storage',
      'rates'
    );

    // Get all CSV configurations
    const configs = await csvConfigRepository.findAll();
    console.log(`📋 Found ${configs.length} CSV configurations\n`);

    let migratedCount = 0;
    let skippedCount = 0;
    let errorCount = 0;

    for (const config of configs) {
      const filename = config.csvFilePath;
      const filePath = path.join(csvDirectory, filename);

      console.log(`📄 Processing: ${config.companyName} - ${filename}`);

      // Check if already in MinIO
      const existingMinioKey = config.metadata?.minioObjectKey as string | undefined;
      if (existingMinioKey) {
        console.log(`   ⏭️  Already in MinIO: ${existingMinioKey}`);
        skippedCount++;
        continue;
      }

      // Check if file exists locally
      if (!fs.existsSync(filePath)) {
        console.log(`   ⚠️  Local file not found: ${filePath}`);
        errorCount++;
        continue;
      }

      try {
        // Read local file
        const fileBuffer = fs.readFileSync(filePath);
        const objectKey = `csv-rates/${filename}`;

        // Upload to MinIO
        await s3Storage.upload({
          bucket,
          key: objectKey,
          body: fileBuffer,
          contentType: 'text/csv',
          metadata: {
            companyName: config.companyName,
            uploadedBy: 'migration-script',
            migratedAt: new Date().toISOString(),
          },
        });

        // Update configuration with MinIO object key
        await csvConfigRepository.update(config.id, {
          metadata: {
            ...config.metadata,
            minioObjectKey: objectKey,
            migratedToMinioAt: new Date().toISOString(),
          },
        });

        console.log(`   ✅ Uploaded to MinIO: ${bucket}/${objectKey}`);
        migratedCount++;
      } catch (error: any) {
        console.log(`   ❌ Error uploading ${filename}: ${error.message}`);
        errorCount++;
      }
    }

    console.log('\n' + '='.repeat(60));
    console.log('📊 Migration Summary:');
    console.log(`   ✅ Migrated: ${migratedCount}`);
    console.log(`   ⏭️  Skipped (already in MinIO): ${skippedCount}`);
    console.log(`   ❌ Errors: ${errorCount}`);
    console.log('='.repeat(60) + '\n');

    if (migratedCount > 0) {
      console.log('🎉 Migration completed successfully!');
    } else if (skippedCount === configs.length) {
      console.log('✅ All files are already in MinIO');
    } else {
      console.log('⚠️  Migration completed with errors');
    }
  } catch (error: any) {
    console.error('❌ Migration failed:', error.message);
    process.exit(1);
  }

  await app.close();
}

migrateCsvFilesToMinio();
