// Cookie-Set/Get Helfer für die Auth. Wir machen das ohne Next.js-Cookies-API,
// damit die Helfer auch im Proxy (Edge Runtime) verwendbar sind.

import { SESSION_COOKIE_NAME } from "./session";

export type SameSite = "Strict" | "Lax" | "None";

const COOKIE_MAX_AGE_SECONDS = 7 * 24 * 60 * 60;

export function buildSessionCookie(token: string, options: { secure: boolean; sameSite?: SameSite } = { secure: true }): string {
  const parts = [
    `${SESSION_COOKIE_NAME}=${token}`,
    "Path=/",
    "HttpOnly",
    `Max-Age=${COOKIE_MAX_AGE_SECONDS}`,
    `SameSite=${options.sameSite ?? "Lax"}`,
  ];
  if (options.secure) parts.push("Secure");
  return parts.join("; ");
}

export function buildLogoutCookie(options: { secure: boolean } = { secure: true }): string {
  const parts = [
    `${SESSION_COOKIE_NAME}=`,
    "Path=/",
    "HttpOnly",
    "Max-Age=0",
    "SameSite=Lax",
  ];
  if (options.secure) parts.push("Secure");
  return parts.join("; ");
}

export function readCookieFromHeader(cookieHeader: string | null | undefined, name: string = SESSION_COOKIE_NAME): string | null {
  if (!cookieHeader) return null;
  for (const part of cookieHeader.split(";")) {
    const [k, ...rest] = part.trim().split("=");
    if (k === name) return rest.join("=");
  }
  return null;
}
