import { MigrationInterface, QueryRunner } from 'typeorm';

export class CreateVehiclesTable1770000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'vehicles' AND table_schema = 'freight') THEN
          CREATE TABLE freight.vehicles (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            plate_number VARCHAR NOT NULL UNIQUE,
            registration_number VARCHAR NOT NULL UNIQUE,
            vehicle_type VARCHAR NOT NULL,
            manufacturer VARCHAR NOT NULL,
            model VARCHAR NOT NULL,
            year INTEGER NOT NULL,
            fuel_type VARCHAR NOT NULL,
            capacity NUMERIC NOT NULL,
            status VARCHAR DEFAULT 'ACTIVE' NOT NULL,
            description TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
            deleted_at TIMESTAMP NULL
          );

          CREATE INDEX idx_vehicles_plate_number ON freight.vehicles(plate_number);
          CREATE INDEX idx_vehicles_registration_number ON freight.vehicles(registration_number);
          CREATE INDEX idx_vehicles_status ON freight.vehicles(status);
          CREATE INDEX idx_vehicles_vehicle_type ON freight.vehicles(vehicle_type);
          CREATE INDEX idx_vehicles_manufacturer ON freight.vehicles(manufacturer);
        END IF;
      END $$;
    `);
  }

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