import { redirect } from "next/navigation";

import { decodeHotelSelection } from "@/components/hotel-review/selection-codec";
import { parseBookingFor } from "@/services/employee-requests/booking-for";
import { HotelReviewClient } from "@/components/hotel-review/HotelReviewClient";

export const dynamic = "force-dynamic";
export const revalidate = 0;
export const fetchCache = "force-no-store";

export const metadata = {
  title: "Request a hotel | Leisure Business",
  description: "Review the hotel and room rate, then send it for approval",
};

interface HotelRequestPageProps {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}

/**
 * LEIS-988/989 — "Review your trip," one page, then the Request-approval
 * overlay (see HotelReviewClient's doc comment for why this is one page
 * rather than a stepper).
 *
 * Same shell shape as app/flight-request/page.tsx: parse, then hand off to
 * the client orchestrator. Unlike that page, there is no fetch here at all —
 * the picked room+rate arrives already-encoded in `?selection=`
 * (OfferDetailsBusiness builds it), because search-service hands back a
 * DIFFERENT `offer.id` on every hotel-details call even for identical
 * params (confirmed live), which ruled out a "re-fetch and look the offer up
 * by id" design — see selection-codec.ts's doc comment for the full story.
 *
 * If the param is missing or fails to decode — a hand-typed URL, a stale
 * bookmark — there is nothing to review, so this redirects to search rather
 * than showing an error about a URL the employee did not type, same rule
 * flight-request follows for a missing clientRef.
 */
export default async function HotelRequestPage({ searchParams }: HotelRequestPageProps) {
  const params = await searchParams;

  const first = (value: string | string[] | undefined): string | undefined =>
    Array.isArray(value) ? value[0] : value;

  const encoded = first(params.selection);
  const selection = encoded ? decodeHotelSelection(encoded) : null;

  if (!selection) {
    redirect("/srp/hotels");
  }

  const bookingFor = parseBookingFor({
    get: (name) => first(params[name]) ?? null,
  });

  return (
    <HotelReviewClient
      key={`${selection.hotelId}:${String(selection.offerSnapshot.offerId)}:${bookingFor ?? "self"}`}
      selection={selection}
      bookingFor={bookingFor}
    />
  );
}
