"use client";

import {
  PendingPaymentOrderStorage,
  type PendingPaymentOrder,
} from "@/data/storage/payment/pending_payment_order_storage";
import {
  DEFAULT_CHARACTER_SLUG,
  getCharacterBySlug,
} from "@/data/constants/character";
import { getCharacterRoutes, ROUTES } from "@/router/routes";
import { buildTipGiftPath } from "@/lib/tip/tip_gift";
import type { Result } from "@/utils/result";

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

export function savePendingEzpayOrder(input: {
  orderId: string;
  subscriptionType: PendingPaymentSubscriptionType;
  giftCategory?: string | null;
  giftPlanId?: string | null;
  returnTo?: PendingPaymentReturnTo;
  characterSlug?: string;
  createdAt?: number;
}): Promise<Result<void>> {
  return PendingPaymentOrderStorage.setPendingOrder({
    orderId: input.orderId,
    payChannel: "ezpay",
    subscriptionType: input.subscriptionType,
    giftCategory: input.giftCategory ?? null,
    giftPlanId: input.giftPlanId ?? null,
    ...(input.returnTo ? { returnTo: input.returnTo } : {}),
    ...(input.characterSlug ? { characterSlug: input.characterSlug } : {}),
    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,
    | "payChannel"
    | "returnTo"
    | "subscriptionType"
    | "characterSlug"
  > &
    Partial<Pick<PendingPaymentOrder, "giftCategory" | "giftPlanId">>,
): string {
  const characterSlug =
    getCharacterBySlug(order.characterSlug)?.slug ?? DEFAULT_CHARACTER_SLUG;
  const characterRoutes = getCharacterRoutes(characterSlug);

  if (order.subscriptionType === "tip") {
    const path = buildTipGiftPath(
      {
        category: order.giftCategory ?? null,
        planId: order.giftPlanId ?? null,
      },
      characterRoutes.tip,
    );
    const separator = path.includes("?") ? "&" : "?";
    return `${path}${separator}payChannel=${order.payChannel}&paymentReturn=1`;
  }

  const params = new URLSearchParams({
    type: order.subscriptionType,
    payChannel: order.payChannel,
    paymentReturn: "1",
  });
  if (order.returnTo) params.set("returnTo", order.returnTo);
  params.set("character", characterSlug);
  return `${ROUTES.subscription}?${params.toString()}`;
}
