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

/**
 * Adds `cost_expected` + `cost_margin` columns to
 * `booking_settlement_masters`.
 *
 * Distinct from `supplier_expected`:
 *
 *   supplier_expected — Σ amount on raised SUPPLIER settlements.
 *                       Only grows when ops assigns a supplier and
 *                       `recordSupplierPayable` fires. Reflects the
 *                       PAYABLE state, not the FORECAST state.
 *
 *   cost_expected     — Σ actual_supplier_cost across booking line
 *                       items (transport + activity). Set at booking-
 *                       create from the Floor snapshot, regardless of
 *                       whether a supplier has been assigned. Reflects
 *                       Mellow's EXPECTED cost basis from day one.
 *
 *   cost_margin       — customer_expected − cost_expected. The honest
 *                       planned-margin number that doesn't lie when
 *                       suppliers haven't been picked yet.
 *
 * Backfills both columns from current line-item snapshots so existing
 * masters reflect the corrected math immediately. Subsequent updates
 * happen via `recomputeMaster` in the settlement service.
 */
export class MasterCostExpected1780700000000 implements MigrationInterface {
  async up(qr: QueryRunner): Promise<void> {
    await qr.query(`
      ALTER TABLE booking_settlement_masters
        ADD COLUMN IF NOT EXISTS cost_expected NUMERIC(12,2) NOT NULL DEFAULT 0,
        ADD COLUMN IF NOT EXISTS cost_margin   NUMERIC(12,2) NOT NULL DEFAULT 0;
    `);

    // Backfill — sum actual_supplier_cost across line items per booking,
    // then write cost_expected + cost_margin onto each existing master.
    await qr.query(`
      WITH line_costs AS (
        SELECT booking_id,
               COALESCE(SUM(actual_supplier_cost), 0) AS cost
          FROM (
            SELECT booking_id, actual_supplier_cost
              FROM booking_transport_items
             WHERE is_deleted = false
             UNION ALL
            SELECT booking_id, actual_supplier_cost
              FROM booking_activity_items
             WHERE is_deleted = false
          ) all_lines
         GROUP BY booking_id
      )
      UPDATE booking_settlement_masters m
         SET cost_expected = COALESCE(lc.cost, 0),
             cost_margin   = COALESCE(m.customer_expected, 0) - COALESCE(lc.cost, 0)
        FROM line_costs lc
       WHERE m.booking_id = lc.booking_id
         AND m.is_deleted = false;
    `);
  }

  async down(qr: QueryRunner): Promise<void> {
    await qr.query(`
      ALTER TABLE booking_settlement_masters
        DROP COLUMN IF EXISTS cost_margin,
        DROP COLUMN IF EXISTS cost_expected;
    `);
  }
}
