import type { PayChannel } from "@/data/dto/payment";
import {
  DEFAULT_TIP_COFFEE_TYPE,
  resolveTipCoffeeType,
  TIP_COFFEE_TYPE_PARAM,
} from "@/lib/tip/tip_coffee";

import { TipScreen } from "./tip-screen";

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

export default async function TipPage({
  searchParams,
}: {
  searchParams: Promise<TipSearchParams>;
}) {
  const query = await searchParams;
  const coffeeType =
    resolveTipCoffeeType(firstSearchParam(query[TIP_COFFEE_TYPE_PARAM])) ??
    DEFAULT_TIP_COFFEE_TYPE;

  return (
    <TipScreen
      coffeeType={coffeeType}
      shouldResumePendingOrder={firstSearchParam(query.paymentReturn) === "1"}
      initialPayChannel={toPayChannel(firstSearchParam(query.payChannel))}
    />
  );
}

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

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