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 error instanceof Error ? error.message : String(error);
}

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

export function defaultAutoRenewForPlan(
  planId: string,
  plans: readonly PaymentPlan[] = [],
): boolean {
  const plan = plans.find((item) => item.planId === planId);
  if (plan?.dolAmount !== null && plan?.dolAmount !== undefined) return false;
  return (
    !planId.includes("lifetime") &&
    !planId.startsWith("dol_") &&
    !planId.startsWith("points_") &&
    !planId.startsWith("credit_")
  );
}

export function getDefaultPlanId(plans: readonly PaymentPlan[]): string {
  return (
    plans.find((plan) => plan.planId === "vip_monthly")?.planId ??
    plans.find((plan) => plan.orderType.startsWith("vip_"))?.planId ??
    plans[0]?.planId ??
    ""
  );
}

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