export type InvoiceErrorCode =
  | 'PROVIDER_REJECTED'
  | 'CREDENTIAL_INVALID'
  | 'PROVIDER_UNAVAILABLE'
  | 'UNSUPPORTED'
  | 'RECONCILE_REQUIRED'

export interface InvoiceError {
  code: InvoiceErrorCode
  message: string
  issued?: 'no' | 'unknown'
}

export function isInvoiceError(value: unknown): value is InvoiceError {
  if (typeof value !== 'object' || value === null) return false
  const candidate = value as { code?: unknown; message?: unknown; issued?: unknown }
  return (
    (candidate.code === 'PROVIDER_REJECTED' ||
      candidate.code === 'CREDENTIAL_INVALID' ||
      candidate.code === 'PROVIDER_UNAVAILABLE' ||
      candidate.code === 'UNSUPPORTED' ||
      candidate.code === 'RECONCILE_REQUIRED') &&
    typeof candidate.message === 'string' &&
    (candidate.issued === undefined || candidate.issued === 'no' || candidate.issued === 'unknown')
  )
}

export function toInvoiceError(value: unknown): InvoiceError {
  if (isInvoiceError(value)) return value
  if (value instanceof Error && value.message.length > 0) {
    return { code: 'PROVIDER_REJECTED', message: value.message }
  }
  return { code: 'PROVIDER_REJECTED', message: 'invoice provider rejected the request' }
}
