/**
 * Data migration: Existing quotations → quotation_options
 *
 * For each existing quotation, creates one QuotationOptionEntity (option_number=1)
 * and updates all child items to point to that option.
 *
 * Run: npx ts-node src/cli/migrate-quotation-options.ts
 *
 * Safe to run multiple times — skips quotations that already have options.
 */
import { DataSource } from 'typeorm';
import * as dotenv from 'dotenv';
import { v4 as uuid } from 'uuid';

dotenv.config();

async function migrate() {
  const ds = new DataSource({
    type: 'postgres',
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT || '5432', 10),
    username: process.env.DB_USERNAME || 'postgres',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'dmc_ops',
  });

  await ds.initialize();
  console.log('Connected to database');

  const queryRunner = ds.createQueryRunner();
  await queryRunner.startTransaction();

  try {
    // Find quotations that don't yet have options
    const quotations = await queryRunner.query(`
      SELECT q.id, q.tenant_id, q.is_selected, q.hotel_total, q.transport_total,
             q.activity_total, q.special_total, q.grand_total, q.created_by, q.updated_by
      FROM quotations q
      WHERE q.is_deleted = false
        AND NOT EXISTS (SELECT 1 FROM quotation_options o WHERE o.quotation_id = q.id)
    `);

    console.log(`Found ${quotations.length} quotations to migrate`);

    for (const q of quotations) {
      const optionId = uuid();

      // Create option for this quotation
      await queryRunner.query(`
        INSERT INTO quotation_options (id, tenant_id, quotation_id, option_number, label, is_selected,
          hotel_total, transport_total, activity_total, special_total, grand_total,
          created_by, updated_by, is_deleted)
        VALUES ($1, $2, $3, 1, 'Option 1', $4, $5, $6, $7, $8, $9, $10, $11, false)
      `, [optionId, q.tenant_id, q.id, q.is_selected, q.hotel_total, q.transport_total,
          q.activity_total, q.special_total, q.grand_total, q.created_by, q.updated_by]);

      // Update child items to point to this option
      for (const table of ['quotation_hotel_items', 'quotation_transport_items', 'quotation_activity_items', 'quotation_special_items']) {
        await queryRunner.query(`
          UPDATE ${table} SET option_id = $1 WHERE quotation_id = $2 AND is_deleted = false
        `, [optionId, q.id]);
      }

      console.log(`  Migrated quotation ${q.id} → option ${optionId}`);
    }

    await queryRunner.commitTransaction();
    console.log(`\nMigration complete. ${quotations.length} quotations migrated.`);
  } catch (error) {
    await queryRunner.rollbackTransaction();
    console.error('Migration failed, rolled back:', error);
  } finally {
    await queryRunner.release();
    await ds.destroy();
  }
}

migrate().catch(console.error);
