import { useContext } from 'react'
import { CheckoutContext, type CheckoutPhase, type CheckoutState } from './context.js'
import type { CheckoutStartInput } from './client.js'
import { CheckoutProviderError } from './errors.js'
import type { StaleSplit } from '@platform-modules/commerce-checkout'
import type { CheckoutWireError, PaymentConfirmError } from './errors.js'

export function useCheckout(): {
  phase: CheckoutPhase
  orderId: string | null
  clientSecret: string | null
  stale: StaleSplit | null
  error: CheckoutWireError | PaymentConfirmError | null
  submit: (input: Omit<CheckoutStartInput, 'idempotencyKey'>) => Promise<void>
  reset: () => void
  retry: () => void
} {
  const ctx = useContext(CheckoutContext)
  if (!ctx) throw new CheckoutProviderError('useCheckout')
  const s: CheckoutState = ctx.state
  return {
    phase: s.phase,
    orderId: s.orderId,
    clientSecret: s.clientSecret,
    stale: s.stale,
    error: s.error,
    submit: ctx.submit,
    reset: ctx.reset,
    retry: ctx.retry,
  }
}