import type { PurchaseStatus } from '@/types/db'
import { PURCHASE_STATUS_LABELS, canTransitionPurchase } from '@/lib/domain/purchases'

/**
 * Refunds as Synchron executes them (S7; contract v0.3.0; Nash, 2026-10-18:
 * "if we executed a partial refund, we show a partial refund; if we executed
 * a full refund, we show a full refund").
 *
 * Synchron refunds each item whole. The purchase carries purchase_status
 * paid | partially_refunded | refunded with refunded_cents and
 * remaining_cents; each item carries its own refunded_cents. This module
 * takes those values already read from the wire (the field mapping is built
 * with S7 once the contract repository is readable) and decides what the
 * buyer sees. Only the buyer sees amounts (Nash, 2026-10-07, item 6). Pure
 * rules, no I/O.
 */
export type SynchronRefundStatus = 'paid' | 'partially_refunded' | 'refunded'

export interface RefundReportItem {
  /** The Workspace purchase item this refund line belongs to. */
  itemId: string
  lineTotalCents: number
  refundedCents: number
}

export interface RefundReport {
  purchaseStatus: SynchronRefundStatus
  refundedCents: number
  remainingCents: number
  items: RefundReportItem[]
}

export type RefundIssue =
  | 'amounts_do_not_add_up'
  | 'status_does_not_match_amounts'
  | 'item_refunds_do_not_match_total'
  | 'item_partly_refunded'
  | 'unknown_item'
  | 'negative_amount'

/** Reasons the Workspace must not apply a report. Empty means it is consistent. */
export function refundReportIssues(
  totalCents: number,
  report: RefundReport,
  knownItemIds: readonly string[] = report.items.map((i) => i.itemId),
): RefundIssue[] {
  const issues = new Set<RefundIssue>()
  const amounts = [report.refundedCents, report.remainingCents, ...report.items.flatMap((i) => [i.lineTotalCents, i.refundedCents])]
  if (amounts.some((n) => !Number.isInteger(n) || n < 0)) issues.add('negative_amount')
  if (report.refundedCents + report.remainingCents !== totalCents) issues.add('amounts_do_not_add_up')
  const expected: SynchronRefundStatus =
    report.refundedCents === 0 ? 'paid' : report.remainingCents === 0 ? 'refunded' : 'partially_refunded'
  if (report.purchaseStatus !== expected) issues.add('status_does_not_match_amounts')
  const itemRefunds = report.items.reduce((sum, i) => sum + i.refundedCents, 0)
  if (report.items.length > 0 && itemRefunds !== report.refundedCents) issues.add('item_refunds_do_not_match_total')
  for (const item of report.items) {
    if (item.refundedCents !== 0 && item.refundedCents !== item.lineTotalCents) issues.add('item_partly_refunded')
    if (!knownItemIds.includes(item.itemId)) issues.add('unknown_item')
  }
  return [...issues]
}

/**
 * The purchase status to store, or null when the report would move the
 * purchase backwards (an older delivery arriving late) and must be ignored.
 */
export function purchaseStatusAfterRefund(current: PurchaseStatus, reported: SynchronRefundStatus): PurchaseStatus | null {
  return canTransitionPurchase(current, reported) ? reported : null
}

export interface BuyerRefundSummary {
  label: string
  originalCents: number
  refundedCents: number
  remainingCents: number
  refundedItemIds: string[]
}

/** What the buyer's billing history shows: original price, refunded, remaining, status. */
export function buyerRefundSummary(totalCents: number, report: RefundReport): BuyerRefundSummary {
  return {
    label: PURCHASE_STATUS_LABELS[report.purchaseStatus],
    originalCents: totalCents,
    refundedCents: report.refundedCents,
    remainingCents: report.remainingCents,
    refundedItemIds: report.items.filter((i) => i.refundedCents > 0).map((i) => i.itemId),
  }
}

/** Other trip participants see the status word only, never amounts. */
export function participantRefundLabel(report: Pick<RefundReport, 'purchaseStatus'>): string {
  return PURCHASE_STATUS_LABELS[report.purchaseStatus]
}
