import { MigrationInterface, QueryRunner } from 'typeorm';

/** Admin-configurable minimum days between today and export RO vessel departure. */
export class SeedRoVesselMinDays1829000000001 implements MigrationInterface {
  name = 'SeedRoVesselMinDays1829000000001';
  private readonly code = 'ro_vessel_min_days';
  private readonly options: Array<{ value: string; label: string }> = [
    { value: '2', label: '2 days' },
    { value: '3', label: '3 days' },
  ];

  public async up(queryRunner: QueryRunner): Promise<void> {
    const existing = await queryRunner.query(
      `SELECT id FROM freight.dropdown_settings WHERE code = $1 LIMIT 1;`,
      [this.code],
    );
    if (existing.length > 0) return;

    const inserted = await queryRunner.query(
      `INSERT INTO freight.dropdown_settings (code, label, description, multiple)
       VALUES ($1, $2, $3, false)
       RETURNING id;`,
      [
        this.code,
        'RO vessel minimum lead time (days)',
        'Minimum days between today and the vessel departure date on an export Release Order.',
      ],
    );
    const settingId = inserted[0].id;

    for (let i = 0; i < this.options.length; i++) {
      const opt = this.options[i];
      await queryRunner.query(
        `INSERT INTO freight.dropdown_options (setting_id, value, label, display_order)
         VALUES ($1, $2, $3, $4);`,
        [settingId, opt.value, opt.label, i],
      );
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DELETE FROM freight.dropdown_settings WHERE code = $1;`, [
      this.code,
    ]);
  }
}
