import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Seed ITMLS US-06 approval chains if missing (standard + bulk).
 */
export class SeedDefaultApprovalRules1749700000000 implements MigrationInterface {
  name = 'SeedDefaultApprovalRules1749700000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      INSERT INTO freight.approval_rules
        (id, requires_director_approval, step_order, required_role, action_label, blocks_role, created_at, updated_at)
      SELECT uuid_generate_v4(), false, 1, 'LINE_STAFF', 'Review & Approve', NULL, now(), now()
      WHERE NOT EXISTS (
        SELECT 1 FROM freight.approval_rules
        WHERE requires_director_approval = false AND step_order = 1 AND deleted_at IS NULL
      );

      INSERT INTO freight.approval_rules
        (id, requires_director_approval, step_order, required_role, action_label, blocks_role, created_at, updated_at)
      SELECT uuid_generate_v4(), false, 2, 'DIRECTOR', 'Final Signature', 'LINE_STAFF', now(), now()
      WHERE NOT EXISTS (
        SELECT 1 FROM freight.approval_rules
        WHERE requires_director_approval = false AND step_order = 2 AND deleted_at IS NULL
      );

      INSERT INTO freight.approval_rules
        (id, requires_director_approval, step_order, required_role, action_label, blocks_role, created_at, updated_at)
      SELECT uuid_generate_v4(), true, 1, 'DIRECTOR', 'Review & Approve', 'LINE_STAFF', now(), now()
      WHERE NOT EXISTS (
        SELECT 1 FROM freight.approval_rules
        WHERE requires_director_approval = true AND step_order = 1 AND deleted_at IS NULL
      );

      INSERT INTO freight.approval_rules
        (id, requires_director_approval, step_order, required_role, action_label, blocks_role, created_at, updated_at)
      SELECT uuid_generate_v4(), true, 2, 'CEO', 'Final Signature', NULL, now(), now()
      WHERE NOT EXISTS (
        SELECT 1 FROM freight.approval_rules
        WHERE requires_director_approval = true AND step_order = 2 AND deleted_at IS NULL
      );
    `);
  }

  public async down(_queryRunner: QueryRunner): Promise<void> {
    // Keep seeded rules on rollback to avoid breaking in-flight bookings.
  }
}
