import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Seeds the admin-configurable "contract validity periods" setting (days). Stored
 * as a dropdown_settings row whose options each hold a day count in `value`, so
 * backoffice manages them through the existing Dropdown Settings UI and the
 * contract staff-accept dialog only offers the configured durations.
 */
export class SeedContractValidityPeriods1792000000004
  implements MigrationInterface
{
  name = 'SeedContractValidityPeriods1792000000004';
  private readonly code = 'contract_validity_periods';
  private readonly options: Array<{ value: string; label: string }> = [
    { value: '180', label: '6 months' },
    { value: '365', label: '1 year' },
    { value: '730', label: '2 years' },
  ];

  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,
        'Contract Validity Periods (days)',
        'Validity durations (in days) a staff can choose when accepting a submitted contract.',
      ],
    );
    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],
    );
  }
}
