"use client";

import {
  PendingPaymentOrderStorage,
  type PendingPaymentOrder,
} from "@/data/storage";
import { ROUTES } from "@/router/routes";
import type { Result } from "@/utils";

export type PendingPaymentSubscriptionType =
  PendingPaymentOrder["subscriptionType"];
export type PendingPaymentReturnTo = PendingPaymentOrder["returnTo"];

export function savePendingEzpayOrder(input: {
  orderId: string;
  subscriptionType: PendingPaymentSubscriptionType;
  returnTo?: PendingPaymentReturnTo;
  createdAt?: number;
}): Promise<Result<void>> {
  return PendingPaymentOrderStorage.setPendingOrder({
    orderId: input.orderId,
    payChannel: "ezpay",
    subscriptionType: input.subscriptionType,
    ...(input.returnTo ? { returnTo: input.returnTo } : {}),
    createdAt: input.createdAt ?? Date.now(),
  });
}

export function getPendingPaymentOrder(): Promise<
  Result<PendingPaymentOrder | null>
> {
  return PendingPaymentOrderStorage.getPendingOrder();
}

export function getPendingPaymentOrderForType(
  subscriptionType: PendingPaymentSubscriptionType,
): Promise<Result<PendingPaymentOrder | null>> {
  return PendingPaymentOrderStorage.getPendingOrderForType(subscriptionType);
}

export function clearPendingPaymentOrder(): Promise<Result<void>> {
  return PendingPaymentOrderStorage.clearPendingOrder();
}

export function buildPendingPaymentSubscriptionUrl(
  order: Pick<PendingPaymentOrder, "subscriptionType" | "returnTo">,
): string {
  const params = new URLSearchParams({
    type: order.subscriptionType,
    paymentReturn: "1",
  });
  if (order.returnTo) params.set("returnTo", order.returnTo);
  return `${ROUTES.subscription}?${params.toString()}`;
}
