import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Bookings no longer run an approval chain — accepting an intake approves the
 * booking outright and generates its contract. The approval chain is now a
 * contract-only concern, so `freight.approval_rules` is read by contracts alone.
 *
 * Also widens the role columns: chain steps now reference IAM position-type
 * keys (`iam.position_types.key`), and real keys run past the old varchar(30)
 * (e.g. '-marketing-manager-/-general-manager' is 38 chars), which would fail
 * on insert.
 */
export class DropBookingApprovalWidenRoles2410000000000
  implements MigrationInterface
{
  name = 'DropBookingApprovalWidenRoles2410000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `DROP TABLE IF EXISTS freight.booking_approval_step;`,
    );

    for (const [table, column] of [
      ['approval_rules', 'required_role'],
      ['approval_rules', 'blocks_role'],
      ['contract_approval_steps', 'required_role'],
      ['contract_approval_steps', 'blocks_role'],
    ] as const) {
      await queryRunner.query(
        `ALTER TABLE freight.${table} ALTER COLUMN ${column} TYPE varchar(64);`,
      );
    }
  }

  /**
   * No-op: the booking approval chain is retired, so re-creating the table
   * would leave dead schema behind. Narrowing the role columns again would
   * truncate any position-type key already stored.
   */
  public async down(): Promise<void> {
    // intentionally empty
  }
}
