import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.bookings
        ALTER COLUMN customer_id DROP NOT NULL;
    `);

    await queryRunner.query(`
      ALTER TABLE freight.bookings
        ADD COLUMN IF NOT EXISTS company_id UUID;
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_bookings_company_id
        ON freight.bookings(company_id);
    `);

    await queryRunner.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (
          SELECT 1 FROM pg_constraint WHERE conname = 'FK_bookings_company_id'
        ) THEN
          ALTER TABLE freight.bookings
            ADD CONSTRAINT "FK_bookings_company_id"
            FOREIGN KEY (company_id)
            REFERENCES freight.companies(id);
        END IF;
      END $$;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.bookings
        DROP CONSTRAINT IF EXISTS "FK_bookings_company_id";
    `);

    await queryRunner.query(`
      UPDATE freight.bookings SET customer_id = company_id WHERE customer_id IS NULL AND company_id IS NOT NULL;
    `);

    await queryRunner.query(`
      ALTER TABLE freight.bookings
        ALTER COLUMN customer_id SET NOT NULL;
    `);
    await queryRunner.query(`
      DROP INDEX IF EXISTS freight.idx_bookings_company_id;
    `);
    await queryRunner.query(`
      ALTER TABLE freight.bookings
        DROP COLUMN IF EXISTS company_id;
    `);
  }
}
