import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Named service items for KM-based maintenance ("oil change", "tires", …).
 * The coarse maintenance_type enum (PREVENTIVE/…) allowed only one interval
 * per type per vehicle, so oil and tire intervals could not coexist. Interval
 * identity becomes (vehicle, maintenance_type, service_item); schedules carry
 * the item so completion re-finds the right interval for auto-scheduling.
 */
export class AddMaintenanceServiceItem2810000000000 implements MigrationInterface {
  name = 'AddMaintenanceServiceItem2810000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `ALTER TABLE freight.maintenance_intervals ADD COLUMN IF NOT EXISTS service_item varchar(120);`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.maintenance_schedules ADD COLUMN IF NOT EXISTS service_item varchar(120);`,
    );
    // Re-key interval uniqueness on (vehicle, type, item). COALESCE folds the
    // item-less legacy rows into one slot; soft-deleted rows are ignored.
    await queryRunner.query(
      `DROP INDEX IF EXISTS freight."UQ_maintenance_intervals_vehicle_type";`,
    );
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_maintenance_intervals_vehicle_type_item"
      ON freight.maintenance_intervals (vehicle_id, maintenance_type, COALESCE(service_item, ''))
      WHERE deleted_at IS NULL;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `DROP INDEX IF EXISTS freight."UQ_maintenance_intervals_vehicle_type_item";`,
    );
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_maintenance_intervals_vehicle_type"
      ON freight.maintenance_intervals (vehicle_id, maintenance_type);
    `);
    await queryRunner.query(
      `ALTER TABLE freight.maintenance_schedules DROP COLUMN IF EXISTS service_item;`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.maintenance_intervals DROP COLUMN IF EXISTS service_item;`,
    );
  }
}
