import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * KM-based maintenance scheduling: per-vehicle service intervals (by km
 * and/or days) driving the maintenance due engine. Raw schema-qualified SQL —
 * the builder API resolved bare table names against the default schema and
 * failed on boot ("Table maintenance_intervals does not exist").
 */
export class AddMaintenanceIntervals2800000000000 implements MigrationInterface {
  name = 'AddMaintenanceIntervals2800000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.maintenance_intervals (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        vehicle_id uuid NOT NULL REFERENCES freight.vehicles(id) ON DELETE CASCADE,
        maintenance_type varchar NOT NULL,
        interval_km numeric(14,2),
        interval_days integer,
        description text,
        is_active boolean NOT NULL DEFAULT true,
        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_maintenance_intervals_vehicle_type"
      ON freight.maintenance_intervals (vehicle_id, maintenance_type);
    `);
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_maintenance_intervals_vehicle_type"
      ON freight.maintenance_intervals (vehicle_id, maintenance_type);
    `);
  }

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