import { type MigrationInterface, type QueryRunner } from 'typeorm';

export class CreateDestinationVehicleTypes1779800000000 implements MigrationInterface {
  async up(qr: QueryRunner): Promise<void> {
    await qr.query(`
      CREATE TABLE IF NOT EXISTS destination_vehicle_types (
        id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        tenant_id       UUID NOT NULL,
        destination_id  UUID NOT NULL REFERENCES destinations(id) ON DELETE CASCADE,
        vehicle_type_id UUID NOT NULL REFERENCES vehicle_types(id) ON DELETE CASCADE,
        is_deleted      BOOLEAN NOT NULL DEFAULT FALSE,
        created_by      UUID,
        updated_by      UUID,
        created_at      TIMESTAMP NOT NULL DEFAULT NOW(),
        updated_at      TIMESTAMP NOT NULL DEFAULT NOW()
      );
    `);
    await qr.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS uq_dvt_tenant_dest_type_active
        ON destination_vehicle_types (tenant_id, destination_id, vehicle_type_id)
        WHERE is_deleted = false;
    `);
    await qr.query(`
      CREATE INDEX IF NOT EXISTS idx_dvt_tenant_destination
        ON destination_vehicle_types (tenant_id, destination_id);
    `);
  }

  async down(qr: QueryRunner): Promise<void> {
    await qr.query(`DROP INDEX IF EXISTS idx_dvt_tenant_destination;`);
    await qr.query(`DROP INDEX IF EXISTS uq_dvt_tenant_dest_type_active;`);
    await qr.query(`DROP TABLE IF EXISTS destination_vehicle_types;`);
  }
}
