import { NestFactory } from '@nestjs/core';
import { AppModule } from '../app.module';
import { TypeOrmCsvRateConfigRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-csv-rate-config.repository';

/**
 * Script to delete orphaned CSV rate configuration
 * Usage: npm run ts-node src/scripts/delete-orphaned-csv-config.ts
 */
async function deleteOrphanedConfig() {
  const app = await NestFactory.createApplicationContext(AppModule);
  const repository = app.get(TypeOrmCsvRateConfigRepository);

  try {
    console.log('🔍 Searching for orphaned test.csv configuration...');

    const configs = await repository.findAll();
    const orphanedConfig = configs.find(c => c.csvFilePath === 'test.csv');

    if (!orphanedConfig) {
      console.log('✅ No orphaned test.csv configuration found');
      await app.close();
      return;
    }

    console.log(
      `📄 Found orphaned config: ${orphanedConfig.companyName} - ${orphanedConfig.csvFilePath}`
    );
    console.log(`   ID: ${orphanedConfig.id}`);
    console.log(`   Uploaded: ${orphanedConfig.uploadedAt}`);

    // Delete the orphaned configuration
    await repository.delete(orphanedConfig.companyName);

    console.log('✅ Successfully deleted orphaned test.csv configuration');
  } catch (error: any) {
    console.error('❌ Error deleting orphaned config:', error.message);
    process.exit(1);
  }

  await app.close();
}

deleteOrphanedConfig();
