import type { PaymentReference, Purchase, PurchaseItem } from '@/types/db'

/**
 * Only the buyer sees what a route purchase cost (Nash, 2026-10-07, items 2
 * and 6). Everyone else on the trip, drivers included, sees the product, its
 * status and when it was bought — never prices, payment references or the
 * buyer's Synchron account. Enforced on the server before data leaves it.
 */
export type ViewerPurchase = Omit<Purchase, 'subtotal_cents' | 'total_amount_cents' | 'synchron_user_token'> & {
  subtotal_cents: number | null
  total_amount_cents: number | null
  synchron_user_token: string | null
}
export type ViewerPurchaseItem = Omit<PurchaseItem, 'unit_price_cents' | 'line_total_cents'> & {
  unit_price_cents: number | null
  line_total_cents: number | null
}
export interface ViewerPurchaseBundle {
  purchase: ViewerPurchase
  items: ViewerPurchaseItem[]
  payment: PaymentReference | null
  /** True only for the person who paid. The screen shows prices and "Continue to payment" only then. */
  is_buyer: boolean
}

export function purchaseForViewer(
  bundle: { purchase: Purchase; items: PurchaseItem[]; payment: PaymentReference | null },
  viewerUserId: string,
): ViewerPurchaseBundle {
  if (bundle.purchase.hha_user_id === viewerUserId) return { ...bundle, is_buyer: true }
  return {
    purchase: { ...bundle.purchase, subtotal_cents: null, total_amount_cents: null, synchron_user_token: null },
    items: bundle.items.map((item) => ({ ...item, unit_price_cents: null, line_total_cents: null })),
    payment: null,
    is_buyer: false,
  }
}
