import type { VoucherState } from '../types.js'

export interface RedeemEvent {
  currentState?: VoucherState
  at: Date
  scanningVendorId?: string
  expiresAt: Date | null
  vendorId: string | null
}

export type RedeemDecision =
  | { ok: true }
  | {
      ok: false
      reason: 'ALREADY_REDEEMED' | 'EXPIRED' | 'WRONG_VENDOR' | 'INVALID'
    }

export function decideRedemption(
  state: VoucherState,
  event: RedeemEvent,
): RedeemDecision {
  const current = event.currentState ?? state

  if (current === 'REDEEMED') {
    return { ok: false, reason: 'ALREADY_REDEEMED' }
  }
  if (current === 'EXPIRED') {
    return { ok: false, reason: 'EXPIRED' }
  }
  if (current === 'CANCELLED') {
    return { ok: false, reason: 'INVALID' }
  }
  if (current !== 'UNREDEEMED') {
    return { ok: false, reason: 'INVALID' }
  }

  if (event.expiresAt !== null && event.expiresAt <= event.at) {
    return { ok: false, reason: 'EXPIRED' }
  }

  if (
    event.vendorId !== null &&
    event.scanningVendorId !== undefined &&
    event.scanningVendorId !== event.vendorId
  ) {
    return { ok: false, reason: 'WRONG_VENDOR' }
  }

  return { ok: true }
}
