import type { PayChannel } from "@/data/schemas/payment";
import type { AppSubscriptionReturnTo } from "@/router/navigation-types";

export type PaymentSearchParamValue = string | string[] | undefined;
export type PaymentSearchParams = Record<string, PaymentSearchParamValue>;

export interface PaymentReturnSearchParams {
  initialPayChannel: PayChannel | null;
  shouldResumePendingOrder: boolean;
}

export function getFirstPaymentSearchParam(
  value: PaymentSearchParamValue,
): string | null {
  return Array.isArray(value) ? (value[0] ?? null) : (value ?? null);
}

export function parsePaymentPayChannel(
  value: PaymentSearchParamValue,
): PayChannel | null {
  const channel = getFirstPaymentSearchParam(value);
  return channel === "ezpay" || channel === "stripe" ? channel : null;
}

export function parsePaymentAutoRenew(
  value: PaymentSearchParamValue,
): boolean | null {
  const autoRenew = getFirstPaymentSearchParam(value);
  if (autoRenew === "1" || autoRenew === "true") return true;
  if (autoRenew === "0" || autoRenew === "false") return false;
  return null;
}

export function parseSubscriptionReturnTo(
  value: PaymentSearchParamValue,
): AppSubscriptionReturnTo {
  const returnTo = getFirstPaymentSearchParam(value);
  if (
    returnTo === "chat" ||
    returnTo === "private-zone" ||
    returnTo === "profile"
  ) {
    return returnTo;
  }
  return null;
}

export function parsePaymentReturnSearchParams(
  searchParams: PaymentSearchParams,
): PaymentReturnSearchParams {
  return {
    initialPayChannel: parsePaymentPayChannel(searchParams.payChannel),
    shouldResumePendingOrder:
      getFirstPaymentSearchParam(searchParams.paymentReturn) === "1",
  };
}
