/* Server-only cookie helpers for the pricing currency.

   Split from currency.ts so the pure module stays import-safe from any
   environment (client components, scripts, tests). This file relies on
   next/headers and must only be called from server contexts. */

import { cookies } from "next/headers";

import { CURRENCY_COOKIE_NAME, type Currency, isSupportedCurrency } from "./currency";

const COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; /* 30 days */

export async function getCurrencyCookie(): Promise<Currency | null> {
  const store = await cookies();
  const value = store.get(CURRENCY_COOKIE_NAME)?.value;
  return isSupportedCurrency(value) ? value : null;
}

/* Persist the user's currency choice. Not httpOnly so the client can read
   it back without a round-trip (e.g. <CurrencySelector/> hydration).
   SameSite=Lax is fine — no cross-site posting needed. */
export async function setCurrencyCookie(c: Currency): Promise<void> {
  const store = await cookies();
  store.set(CURRENCY_COOKIE_NAME, c, {
    maxAge: COOKIE_MAX_AGE_SECONDS,
    sameSite: "lax",
    httpOnly: false,
    path: "/",
  });
}
