import { type EntityManager } from 'typeorm';
import { SeasonEntity } from '../../entities/season.entity';
import { findMatchingSeasonId } from '../../common/utils/season-date';

/**
 * Supplier cost of a transport line from the Supplier Pricing master
 * (`supplier_cost_prices`) — per unit (per vehicle for PVT, per seat for
 * SIC). This is the default `actual_supplier_cost` basis (client rule
 * 2026-10-17); the Floor Price is only the minimum SELLING guard and is
 * never a cost.
 *
 * - `supplier_id` given → that supplier's cost.
 * - no supplier → the LOWEST cost across suppliers.
 * A season-specific row for the date wins over the all-season row.
 * Returns null when no supplier row matches.
 */
export interface SupplierCostInput {
  tenant_id: string;
  destination_id: string | null;
  transport_service_id: string;
  vehicle_type_id: string | null | undefined;
  is_shared: boolean;
  date: string | null | undefined;
  supplier_id?: string | null;
}

export async function resolveSupplierUnitCost(
  manager: EntityManager,
  input: SupplierCostInput,
): Promise<number | null> {
  if (!input.transport_service_id) return null;
  const isSic = !!input.is_shared;
  if (!isSic && !input.vehicle_type_id) return null;

  let seasonId: string | null = null;
  if (input.date && input.destination_id) {
    const seasons = await manager.find(SeasonEntity, {
      where: {
        destination_id: input.destination_id,
        tenant_id: input.tenant_id,
        is_deleted: false,
        is_active: true,
      },
    });
    seasonId = findMatchingSeasonId(seasons, input.date);
  }

  const params: Array<string> = [
    input.tenant_id,
    input.transport_service_id,
    isSic ? 'SIC' : 'PVT',
  ];
  const p = (v: string) => {
    params.push(v);
    return `$${params.length}`;
  };
  const vehicleSql = isSic
    ? 'vehicle_type_id IS NULL'
    : `vehicle_type_id = ${p(input.vehicle_type_id as string)}`;
  const seasonSql = seasonId
    ? `(season_id IS NULL OR season_id = ${p(seasonId)})`
    : 'season_id IS NULL';
  const supplierSql = input.supplier_id ? `AND supplier_id = ${p(input.supplier_id)}` : '';
  // Only compare prices in the destination's cost currency (rows with no
  // currency are treated as destination currency) — the cost basis and
  // payables are in that currency, and MIN() across currencies is
  // meaningless (GBP 45 vs AED 40).
  let currencySql = '';
  if (input.destination_id) {
    const dest = (await manager.query(
      'SELECT currency_id FROM destinations WHERE id = $1 AND tenant_id = $2',
      [input.destination_id, input.tenant_id],
    )) as Array<{ currency_id: string | null }>;
    const destCurrency = dest[0]?.currency_id;
    if (destCurrency) currencySql = `AND (currency_id IS NULL OR currency_id = ${p(destCurrency)})`;
  }

  const rows = (await manager.query(
    `
    SELECT MIN(picked.cost_price)::float AS cost
      FROM (
        SELECT DISTINCT ON (supplier_id) cost_price
          FROM supplier_cost_prices
         WHERE tenant_id = $1
           AND transport_service_id = $2
           AND mode = $3
           AND is_deleted = false
           AND is_active = true
           AND ${seasonSql}
           AND ${vehicleSql}
           ${supplierSql}
           ${currencySql}
         ORDER BY supplier_id, CASE WHEN season_id IS NOT NULL THEN 0 ELSE 1 END
      ) picked
    `,
    params,
  )) as Array<{ cost: number | null }>;
  return rows?.[0]?.cost != null ? Number(rows[0].cost) : null;
}
