import type { PayChannel } from "@/data/schemas/payment";
import { AppEnvUtil } from "@/utils/app-env";

import { getDefaultPayChannelForCountryCode } from "./default_pay_channel";

export interface PaymentMethodConfig {
  canChoosePaymentMethod: boolean;
  ezpayDisplayName?: "GCash" | "QRIS";
  initialPayChannel: PayChannel;
  showPaymentMethodSelector: boolean;
}

export function canChoosePayChannel(
  countryCode: string | null | undefined,
): boolean {
  if (!AppEnvUtil.isProduction()) return true;
  return isRegionalEzpayCountryCode(countryCode);
}

export function resolvePayChannel(input: {
  countryCode: string | null | undefined;
  requestedPayChannel: PayChannel | null | undefined;
}): PayChannel {
  if (!canChoosePayChannel(input.countryCode)) return "stripe";
  return (
    input.requestedPayChannel ??
    getDefaultPayChannelForCountryCode(input.countryCode)
  );
}

export function getPaymentMethodConfig(input: {
  countryCode: string | null | undefined;
  requestedPayChannel: PayChannel | null | undefined;
}): PaymentMethodConfig {
  return {
    canChoosePaymentMethod: canChoosePayChannel(input.countryCode),
    ezpayDisplayName: isIndonesiaCountryCode(input.countryCode)
      ? "QRIS"
      : "GCash",
    initialPayChannel: resolvePayChannel(input),
    showPaymentMethodSelector: isRegionalEzpayCountryCode(input.countryCode),
  };
}

function isRegionalEzpayCountryCode(
  countryCode: string | null | undefined,
): boolean {
  const normalizedCountryCode = countryCode?.trim().toUpperCase();
  return normalizedCountryCode === "PH" || normalizedCountryCode === "ID";
}

function isIndonesiaCountryCode(
  countryCode: string | null | undefined,
): boolean {
  return countryCode?.trim().toUpperCase() === "ID";
}
