import { MigrationInterface, QueryRunner } from 'typeorm';

export class CreateDriversTable1775000000000 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 = 'drivers' AND table_schema = 'freight') THEN
          CREATE TABLE freight.drivers (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            license_number VARCHAR NOT NULL UNIQUE,
            first_name VARCHAR NOT NULL,
            last_name VARCHAR NOT NULL,
            email VARCHAR NOT NULL UNIQUE,
            phone_number VARCHAR NOT NULL UNIQUE,
            date_of_birth DATE NOT NULL,
            license_expiry_date DATE NOT NULL,
            status VARCHAR DEFAULT 'ACTIVE' NOT NULL,
            vehicle_types_authorized VARCHAR[],
            address TEXT,
            emergency_contact VARCHAR,
            notes TEXT,
            total_trips INTEGER DEFAULT 0,
            rating NUMERIC(3, 2),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
            deleted_at TIMESTAMP NULL
          );

          CREATE INDEX idx_drivers_license_number ON freight.drivers(license_number);
          CREATE INDEX idx_drivers_email ON freight.drivers(email);
          CREATE INDEX idx_drivers_phone_number ON freight.drivers(phone_number);
          CREATE INDEX idx_drivers_status ON freight.drivers(status);
        END IF;
      END $$;
    `);
  }

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