import { type MigrationInterface, type QueryRunner } from 'typeorm';

/**
 * VehicleTypeJunkCleanup1781000000000 soft-deleted the junk "O"
 * vehicle type at the master level but left orphan rows behind:
 *
 *   - transport_pricing rows where vehicle_type_id points at a
 *     now-soft-deleted vehicle_type (16 rows on the mellow tenant)
 *   - destination_vehicle_types mappings linking destinations to
 *     soft-deleted types (1 row on the mellow tenant)
 *
 * The orphan pricing rows kept surfacing on Transport Pricing because
 * the FE reads from `transport_pricing` joined to `vehicle_types` and
 * the BE list query didn't filter on the master's `is_deleted` flag.
 *
 * This migration cleans both. Idempotent — re-running against an
 * already-clean tenant is a no-op.
 */
export class VehicleTypeOrphanCascade1781400000000 implements MigrationInterface {
  public async up(qr: QueryRunner): Promise<void> {
    // Soft-delete orphan pricing rows. Tenant-scoping is implicit
    // because vehicle_types.id is globally unique within a tenant; the
    // join handles scoping.
    await qr.query(`
      UPDATE transport_pricing tp
         SET is_deleted = true,
             updated_at = NOW()
        FROM vehicle_types vt
       WHERE tp.vehicle_type_id = vt.id
         AND vt.is_deleted = true
         AND tp.is_deleted = false;
    `);
    // destination_vehicle_types is a pure mapping table; delete
    // (not soft-delete) orphan rows since there's no audit value.
    await qr.query(`
      DELETE FROM destination_vehicle_types dvt
       USING vehicle_types vt
       WHERE dvt.vehicle_type_id = vt.id
         AND vt.is_deleted = true;
    `);
  }

  public async down(): Promise<void> {
    // Irreversible — we cleaned junk forward. Bringing back the
    // pricing rows would re-introduce the very rows the FE was meant
    // to hide.
  }
}
