import type { Cart, CartLine, PriceSnapshot } from '@platform-modules/commerce-cart'
import type { BuyerRef, Order, OrdersSchema, ProductKind } from '@platform-modules/commerce-orders'
import type { FulfillmentPorts } from '@platform-modules/commerce-fulfillment'
import type {
  ChargeResult,
  IntentStore,
  PaymentProvider,
  SettleChargeDeps,
} from '@platform-modules/billing'
import type { Transaction, TransactionalDatabase } from '@platform-modules/db'

export type CheckoutInput = {
  cartId?: string
  cart?: Cart
  buyerRef: { userId: string }
  priceMode: 'inclusive' | 'exclusive'
  currency: string
  buyerCountry: string
  idempotencyKey: string
}

export type CheckoutDeps<S extends OrdersSchema = OrdersSchema> = Omit<
  SettleChargeDeps<S>,
  'db'
> & {
  db: TransactionalDatabase<S>
  fulfillment: FulfillmentPorts
  onSettle?: (tx: Transaction<S>, order: Order) => Promise<void>
}

export type PricedLine = {
  variantId: string
  qty: number
  unitNet: bigint
  vat: bigint
  lineTotal: bigint
}

export type StaleSplit = {
  removed: string[]
  updated: { variantId: string; was: bigint; now: bigint }[]
}

export type CatalogEntry = {
  available: boolean
  price: PriceSnapshot
  kind: ProductKind
  title?: string
  /** Catalog product's vendorId — the authoritative source for money attribution (cart lines are client-shaped). */
  vendorId?: string | null
}

/** Checkout-local catalog view — assembled in startCheckout from commerce-catalog reads. */
export type CatalogSnapshot = ReadonlyMap<string, CatalogEntry>

export type { BuyerRef, Cart, CartLine, ChargeResult, IntentStore, Order, OrdersSchema, PaymentProvider, PriceSnapshot }
