import { MigrationInterface, QueryRunner } from 'typeorm';

export class BookingFlowRefactor1749200000000 implements MigrationInterface {
  name = 'BookingFlowRefactor1749200000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.booking_review_note (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        booking_id UUID NOT NULL REFERENCES freight.bookings(id) ON DELETE CASCADE,
        author_id UUID,
        note TEXT NOT NULL,
        type VARCHAR(30) NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        deleted_at TIMESTAMPTZ
      );
      CREATE INDEX IF NOT EXISTS idx_booking_review_note_booking_id
        ON freight.booking_review_note(booking_id);
    `);

    await queryRunner.query(`
      ALTER TABLE freight.bookings
        ADD COLUMN IF NOT EXISTS marketing_approved_by_id UUID,
        ADD COLUMN IF NOT EXISTS marketing_approved_at TIMESTAMPTZ,
        ADD COLUMN IF NOT EXISTS contract_summary TEXT,
        ADD COLUMN IF NOT EXISTS locked_at TIMESTAMPTZ;
    `);

    await queryRunner.query(`
      UPDATE freight.bookings SET status = 'SUBMITTED'
        WHERE status IN ('RFQ_SUBMITTED', 'QUOTATION_SENT', 'QUOTATION_APPROVED');
      UPDATE freight.bookings SET status = 'REJECTED'
        WHERE status = 'QUOTATION_REJECTED';
      UPDATE freight.bookings SET status = 'CANCELLED'
        WHERE status = 'CANCELLED';
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.bookings
        DROP COLUMN IF EXISTS locked_at,
        DROP COLUMN IF EXISTS contract_summary,
        DROP COLUMN IF EXISTS marketing_approved_at,
        DROP COLUMN IF EXISTS marketing_approved_by_id;
    `);
    await queryRunner.query(`DROP TABLE IF EXISTS freight.booking_review_note;`);
  }
}
