"use client";

import {
  PendingPaymentOrderStorage,
  type PendingPaymentOrder,
} from "@/data/storage/payment/pending_payment_order_storage";
import { ROUTES } from "@/router/routes";
import {
  DEFAULT_TIP_COFFEE_TYPE,
  TIP_COFFEE_TYPE_PARAM,
} from "@/lib/tip/tip_coffee";
import type { Result } from "@/utils/result";

export type PendingPaymentSubscriptionType =
  PendingPaymentOrder["subscriptionType"];
export type PendingPaymentReturnTo = PendingPaymentOrder["returnTo"];
export type PendingPaymentTipCoffeeType = NonNullable<
  PendingPaymentOrder["tipCoffeeType"]
>;

export function savePendingEzpayOrder(input: {
  orderId: string;
  subscriptionType: PendingPaymentSubscriptionType;
  tipCoffeeType?: PendingPaymentTipCoffeeType;
  returnTo?: PendingPaymentReturnTo;
  createdAt?: number;
}): Promise<Result<void>> {
  return PendingPaymentOrderStorage.setPendingOrder({
    orderId: input.orderId,
    payChannel: "ezpay",
    subscriptionType: input.subscriptionType,
    ...(input.tipCoffeeType ? { tipCoffeeType: input.tipCoffeeType } : {}),
    ...(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,
    "payChannel" | "returnTo" | "subscriptionType" | "tipCoffeeType"
  >,
): string {
  if (order.subscriptionType === "tip") {
    const params = new URLSearchParams({
      payChannel: order.payChannel,
      paymentReturn: "1",
      [TIP_COFFEE_TYPE_PARAM]:
        order.tipCoffeeType ?? DEFAULT_TIP_COFFEE_TYPE,
    });
    return `${ROUTES.tip}?${params.toString()}`;
  }

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