import type { Repository } from 'typeorm';
import { computeHotelStayTotal } from './hotel-totals';

/**
 * Recompute + persist `parent.subtotal` from the current child rows.
 *
 * The main save paths (quote save, booking itinerary edit, convert
 * from quote, quick booking) already recompute `subtotal` inline,
 * because they know the periods + extras array being written. This
 * helper exists for the OTHER case: any future patch endpoint that
 * touches ONLY the children (e.g. an inline "edit this period's
 * rate" popover) — without a helper, that path would leave
 * `parent.subtotal` stale.
 *
 * Idempotent. Safe to call multiple times per save; only issues one
 * UPDATE.
 */
interface HotelPeriodLike {
  hotel_item_id: string;
  nights?: number[];
  num_rooms: number;
  rate_per_night: number;
}
interface HotelExtraLike {
  hotel_item_id: string;
  nights?: number[];
  quantity: number;
  rate: number;
  scale_by_rooms?: boolean;
}
interface HotelStayLike {
  id: string;
  tenant_id: string;
}

export async function refreshHotelStayTotal(
  hotelItemId: string,
  tenantId: string,
  itemRepo: Repository<HotelStayLike & { subtotal: number }>,
  periodRepo: Repository<HotelPeriodLike & { is_deleted: boolean; tenant_id: string }>,
  extraRepo: Repository<HotelExtraLike & { is_deleted: boolean; tenant_id: string }>,
): Promise<number> {
  const [periods, extras] = await Promise.all([
    periodRepo.find({
      where: { hotel_item_id: hotelItemId, tenant_id: tenantId, is_deleted: false },
    }),
    extraRepo.find({
      where: { hotel_item_id: hotelItemId, tenant_id: tenantId, is_deleted: false },
    }),
  ]);
  const subtotal = computeHotelStayTotal(periods, extras);
  await itemRepo.update({ id: hotelItemId, tenant_id: tenantId }, { subtotal });
  return subtotal;
}
