import { cookies } from 'next/headers'; export const TOKEN_COOKIE = 'tower_token'; export const MEMBER_COOKIE = 'tower_member_token'; const MEMBER_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; export function getApiBaseUrl(): string { return process.env['API_URL'] ?? 'http://localhost:3001'; } export async function getToken(): Promise { const store = await cookies(); return store.get(TOKEN_COOKIE)?.value; } export async function getMemberToken(): Promise { const store = await cookies(); return store.get(MEMBER_COOKIE)?.value; } function withAuthHeader(headers: Headers, token: string | undefined): void { headers.set('Accept', 'application/json'); if (token && !headers.has('Authorization')) { headers.set('Authorization', `Bearer ${token}`); } } export async function apiFetch(path: string, init: RequestInit = {}): Promise { const token = await getToken(); const headers = new Headers(init.headers); withAuthHeader(headers, token); if (init.body && !headers.has('Content-Type')) { headers.set('Content-Type', 'application/json'); } return fetch(`${getApiBaseUrl()}${path}`, { ...init, headers, cache: 'no-store' }); } export async function memberApiFetch(path: string, init: RequestInit = {}): Promise { const token = await getMemberToken(); const headers = new Headers(init.headers); withAuthHeader(headers, token); if (init.body && !headers.has('Content-Type')) { headers.set('Content-Type', 'application/json'); } return fetch(`${getApiBaseUrl()}${path}`, { ...init, headers, cache: 'no-store' }); } export function buildMemberCookie(token: string): string { return `${MEMBER_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${MEMBER_MAX_AGE_SECONDS}`; } export function clearMemberCookie(): string { return `${MEMBER_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`; } export function jsonResponse(body: unknown, status = 200, extraHeaders: Record = {}): Response { return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', ...extraHeaders }, }); }