import { ExceptionHandler } from "@/core/errors";
import type { PaymentPlan } from "@/data/dto/payment";

import type { PaymentState } from "../payment-state";

export const MAX_ORDER_POLLING_MS = 5 * 60 * 1000;
export const PAYMENT_TIMEOUT_ERROR_MESSAGE =
  "Payment timed out. Please try again.";

export function toPaymentErrorMessage(error: unknown): string {
  return ExceptionHandler.message(error);
}

export function hasOrderPollingTimedOut(
  startedAt: number | null,
  now = Date.now(),
  maxDurationMs = MAX_ORDER_POLLING_MS,
): boolean {
  return startedAt !== null && now - startedAt >= maxDurationMs;
}

export function resetOrderState(): Partial<PaymentState> {
  return {
    currentOrderId: null,
    currentOrderPlanId: null,
    payParams: null,
    orderStatus: null,
    orderPollingStartedAt: null,
    errorMessage: null,
  };
}

export function getSelectedPlan(context: PaymentState): PaymentPlan | undefined {
  return context.plans.find(
    (plan) => plan.planId === context.selectedPlanId,
  );
}

export function getCurrentOrderPlan(
  context: PaymentState,
): PaymentPlan | undefined {
  if (!context.currentOrderPlanId) return undefined;
  return context.plans.find(
    (plan) => plan.planId === context.currentOrderPlanId,
  );
}
