import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Approval workflow for priority-rule changes: every create/update/delete of a
 * priority config is filed here as a PENDING change request; an approver
 * applies or rejects it. `payload` carries the proposed field values (null for
 * DELETE), `priority_config_id` the target row (null for CREATE).
 */
export class CreatePriorityRuleChangeRequests2250000000000
  implements MigrationInterface
{
  name = 'CreatePriorityRuleChangeRequests2250000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.priority_rule_change_requests (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        action varchar(10) NOT NULL,
        priority_config_id uuid NULL REFERENCES freight.priority_configs (id),
        payload jsonb NULL,
        status varchar(10) NOT NULL DEFAULT 'PENDING',
        requested_by_user_id uuid NULL,
        decided_by_user_id uuid NULL,
        decided_at timestamptz NULL,
        decision_note text NULL,
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        deleted_at timestamptz NULL
      )
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_prcr_status
        ON freight.priority_rule_change_requests (status)
    `);
  }

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