import type { PayChannel } from "@/data/dto/payment";
import {
  PAYMENT_ANALYTICS_ENTRY_PARAM,
  PAYMENT_ANALYTICS_REASON_PARAM,
  parsePaymentAnalyticsContext,
} from "@/lib/analytics/payment_analytics_context";

import {
  SubscriptionScreen,
  type SubscriptionType,
} from "./subscription-screen";

type SubscriptionSearchParams = Record<string, string | string[] | undefined>;

export default async function SubscriptionPage({
  searchParams,
}: {
  searchParams: Promise<SubscriptionSearchParams>;
}) {
  const query = await searchParams;
  const subscriptionType = toSubscriptionType(firstSearchParam(query.type));
  const analyticsContext = parsePaymentAnalyticsContext({
    entryPoint: firstSearchParam(query[PAYMENT_ANALYTICS_ENTRY_PARAM]),
    triggerReason: firstSearchParam(query[PAYMENT_ANALYTICS_REASON_PARAM]),
    subscriptionType,
  });

  return (
    <SubscriptionScreen
      subscriptionType={subscriptionType}
      shouldResumePendingOrder={firstSearchParam(query.paymentReturn) === "1"}
      returnTo={toReturnTo(firstSearchParam(query.returnTo))}
      initialPayChannel={toPayChannel(firstSearchParam(query.payChannel))}
      analyticsContext={analyticsContext}
    />
  );
}

function firstSearchParam(value: string | string[] | undefined): string | null {
  return Array.isArray(value) ? (value[0] ?? null) : (value ?? null);
}

function toSubscriptionType(value: string | null): SubscriptionType {
  return value === "topup" ? "topup" : "vip";
}

function toReturnTo(value: string | null): "chat" | null {
  return value === "chat" ? "chat" : null;
}

function toPayChannel(value: string | null): PayChannel | null {
  return value === "ezpay" || value === "stripe" ? value : null;
}
