import { createContext } from 'react'
import type { PaymentConfirmError } from './errors'

/** Result of a client-side confirm. Neutral — no PSP type leaks. */
export type PaymentConfirmResult =
  | {
      /**
       * Client-side success ONLY — NOT settlement. The order is fulfilled by the SERVER webhook
       * (billing.ingestWebhook → checkout settlement). Navigate to a server-truth order-status screen;
       * NEVER render fulfillment ('download ready', 'access granted') off this client result — the
       * webhook may lag.
       */
      kind: 'succeeded'
    }
  | { kind: 'requires_redirect' }
  | { kind: 'error'; error: PaymentConfirmError }

export interface ConfirmPaymentOptions {
  /** URL the PSP redirects back to for redirect-based methods / 3DS fallback. REQUIRED by every PSP confirm. */
  returnUrl: string
}

/** The neutral context a PSP provider populates. */
export interface PaymentUiContextValue {
  /** True once the PSP element is mounted + ready to accept input. */
  ready: boolean
  /** Confirm the payment client-side. Neutral result; PSP-specific confirm lives in the provider. */
  confirm: (opts: ConfirmPaymentOptions) => Promise<PaymentConfirmResult>
  /** Set if the PSP element failed to initialise (load/config error). */
  error: import('./errors').PaymentProviderError | null
}

/** null default → hooks throw "outside provider" rather than read a stale value. */
export const PaymentUiContext = createContext<PaymentUiContextValue | null>(null)