import {
  PAYMENT_ANALYTICS_ENTRY_PARAM,
  PAYMENT_ANALYTICS_REASON_PARAM,
  parsePaymentAnalyticsContext,
} from "@/lib/analytics/payment_analytics_context";
import {
  getFirstPaymentSearchParam,
  parsePaymentReturnSearchParams,
  parseSubscriptionReturnTo,
  type PaymentSearchParams,
} from "@/lib/payment/payment_search_params";
import {
  DEFAULT_CHARACTER_SLUG,
  getCharacterBySlug,
} from "@/data/constants/character";

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

export default async function SubscriptionPage({
  searchParams,
}: {
  searchParams: Promise<PaymentSearchParams>;
}) {
  const query = await searchParams;
  const paymentReturn = parsePaymentReturnSearchParams(query);
  const subscriptionType = toSubscriptionType(
    getFirstPaymentSearchParam(query.type),
  );
  const sourceCharacterSlug =
    getCharacterBySlug(getFirstPaymentSearchParam(query.character))?.slug ??
    DEFAULT_CHARACTER_SLUG;
  const initialPlanId = getFirstPaymentSearchParam(query.planId);
  const commercialOfferId = getFirstPaymentSearchParam(
    query.commercialOfferId,
  );
  const resumeOrderId = getFirstPaymentSearchParam(query.resumeOrderId);
  const chatActionId = getFirstPaymentSearchParam(query.chatActionId);
  const analyticsContext = parsePaymentAnalyticsContext({
    entryPoint: getFirstPaymentSearchParam(
      query[PAYMENT_ANALYTICS_ENTRY_PARAM],
    ),
    triggerReason: getFirstPaymentSearchParam(
      query[PAYMENT_ANALYTICS_REASON_PARAM],
    ),
    subscriptionType,
  });

  return (
    <SubscriptionScreen
      subscriptionType={subscriptionType}
      shouldResumePendingOrder={paymentReturn.shouldResumePendingOrder}
      returnTo={parseSubscriptionReturnTo(query.returnTo)}
      initialPayChannel={paymentReturn.initialPayChannel}
      analyticsContext={analyticsContext}
      sourceCharacterSlug={sourceCharacterSlug}
      initialPlanId={initialPlanId}
      commercialOfferId={commercialOfferId}
      resumeOrderId={resumeOrderId}
      chatActionId={chatActionId}
    />
  );
}

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