import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Vehicle Compliance & Expiry Alerts.
 * - Adds expiry-tracking columns to freight.vehicles.
 * - Creates freight.compliance_records for per-document compliance tracking.
 */
export class AddVehicleCompliance1950000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // Vehicle expiry / compliance columns.
    await queryRunner.query(`
      ALTER TABLE freight.vehicles
        ADD COLUMN IF NOT EXISTS vin VARCHAR,
        ADD COLUMN IF NOT EXISTS ownership VARCHAR,
        ADD COLUMN IF NOT EXISTS insurance_expiry DATE,
        ADD COLUMN IF NOT EXISTS registration_expiry DATE,
        ADD COLUMN IF NOT EXISTS next_inspection_date DATE;
    `);

    // Compliance records table.
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.compliance_records (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        vehicle_id UUID NOT NULL REFERENCES freight.vehicles(id),
        type VARCHAR NOT NULL,
        document_number VARCHAR,
        issued_date DATE,
        expiry_date DATE NOT NULL,
        status VARCHAR NOT NULL DEFAULT 'VALID',
        notes TEXT,
        created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        deleted_at TIMESTAMPTZ
      );
    `);

    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS idx_compliance_records_vehicle_id ON freight.compliance_records(vehicle_id);`,
    );
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS idx_compliance_records_expiry_date ON freight.compliance_records(expiry_date);`,
    );
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS idx_compliance_records_type ON freight.compliance_records(type);`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE IF EXISTS freight.compliance_records CASCADE;`);
    await queryRunner.query(`
      ALTER TABLE freight.vehicles
        DROP COLUMN IF EXISTS vin,
        DROP COLUMN IF EXISTS ownership,
        DROP COLUMN IF EXISTS insurance_expiry,
        DROP COLUMN IF EXISTS registration_expiry,
        DROP COLUMN IF EXISTS next_inspection_date;
    `);
  }
}
