import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Seeds the global "general contract period" setting (months). Stored as a
 * dropdown_settings row with a single option whose `value` holds the month count
 * so backoffice can manage it through the existing settings UI later.
 */
export class SeedGeneralContractPeriod1792000000003
  implements MigrationInterface
{
  name = 'SeedGeneralContractPeriod1792000000003';
  private readonly code = 'general_contract_period';

  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,
        'General Contract Period (months)',
        'How many months a general contract stays open for ordering after activation.',
      ],
    );
    const settingId = inserted[0].id;

    await queryRunner.query(
      `INSERT INTO freight.dropdown_options (setting_id, value, label, display_order)
       VALUES ($1, $2, $3, 0);`,
      [settingId, '3', '3 months'],
    );
  }

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