import { cookies } from 'next/headers';
import { AUTH_CONFIG } from './auth-config';
import type { AuthResponse, AuthUser } from './auth-types';

/**
 * Server-side helpers for handling auth cookies. All called from API route
 * handlers (Node runtime) — never from the browser.
 *
 * Why cookies for tokens (instead of returning JSON to localStorage)?
 *   - HttpOnly: JS can't read them → no XSS exfiltration
 *   - SameSite=lax: not sent on cross-site form posts → CSRF defence
 *   - Auto-sent by browser on subsequent requests → simpler client code
 */

const TWO_HOURS = 60 * 60 * 2;
const SEVEN_DAYS = 60 * 60 * 24 * 7;

export async function setAuthCookies(auth: AuthResponse): Promise<void> {
  const jar = await cookies();
  jar.set(AUTH_CONFIG.cookies.accessToken, auth.accessToken, {
    ...AUTH_CONFIG.cookieOptions,
    maxAge: auth.expiresIn ?? TWO_HOURS,
  });
  jar.set(AUTH_CONFIG.cookies.refreshToken, auth.refreshToken, {
    ...AUTH_CONFIG.cookieOptions,
    maxAge: SEVEN_DAYS,
  });
  // User profile is non-sensitive snapshot data — readable by client JS.
  jar.set(AUTH_CONFIG.cookies.user, JSON.stringify(auth.user), {
    ...AUTH_CONFIG.cookieOptions,
    httpOnly: false,
    maxAge: SEVEN_DAYS,
  });
}

export async function clearAuthCookies(): Promise<void> {
  const jar = await cookies();
  jar.delete(AUTH_CONFIG.cookies.accessToken);
  jar.delete(AUTH_CONFIG.cookies.refreshToken);
  jar.delete(AUTH_CONFIG.cookies.user);
}

export async function readAccessToken(): Promise<string | null> {
  const jar = await cookies();
  return jar.get(AUTH_CONFIG.cookies.accessToken)?.value ?? null;
}

export async function readRefreshToken(): Promise<string | null> {
  const jar = await cookies();
  return jar.get(AUTH_CONFIG.cookies.refreshToken)?.value ?? null;
}

export async function readUserFromCookie(): Promise<AuthUser | null> {
  const jar = await cookies();
  const raw = jar.get(AUTH_CONFIG.cookies.user)?.value;
  if (!raw) return null;
  try {
    return JSON.parse(raw) as AuthUser;
  } catch {
    return null;
  }
}
