/**
 * Session-cookie helpers. After successful JWT validation, Mailforge writes
 * a short-lived session cookie so subsequent same-origin requests don't need
 * to carry the JWT in headers.
 *
 * The cookie holds the raw JWT, not a derived session — so a single source
 * of truth (host-CRM-signed JWT) governs identity.
 *
 * Cookie scope: HTTP-only, SameSite=Lax (Strict would block the initial
 * redirect from Laravel). `Secure` follows `MAILFORGE_BASE_URL` (https → on)
 * or optional `MAILFORGE_COOKIE_SECURE=true|false`; if the base URL is unset,
 * falls back to `NODE_ENV === 'production'` for backwards compatibility.
 */

import type { NextRequest, NextResponse } from 'next/server';

const COOKIE_NAME = 'mf_session';

function sessionCookieSecure(): boolean {
  const o = process.env.MAILFORGE_COOKIE_SECURE?.trim().toLowerCase();
  if (o === 'true' || o === '1') return true;
  if (o === 'false' || o === '0') return false;
  const base = process.env.MAILFORGE_BASE_URL?.trim() ?? '';
  if (base.startsWith('https://')) return true;
  if (base.startsWith('http://')) return false;
  return process.env.NODE_ENV === 'production';
}

interface SetSessionCookieOpts {
  response: NextResponse;
  token: string;
  /** Cookie lifetime in seconds. Defaults to 15 minutes (matches default JWT TTL). */
  maxAge?: number;
}

export function setSessionCookie({ response, token, maxAge = 900 }: SetSessionCookieOpts): void {
  response.cookies.set({
    name: COOKIE_NAME,
    value: token,
    httpOnly: true,
    sameSite: 'lax',
    secure: sessionCookieSecure(),
    path: '/',
    maxAge,
  });
}

export function readSessionCookie(req: NextRequest): string | undefined {
  return req.cookies.get(COOKIE_NAME)?.value;
}

export function clearSessionCookie(response: NextResponse): void {
  response.cookies.set({
    name: COOKIE_NAME,
    value: '',
    httpOnly: true,
    sameSite: 'lax',
    secure: sessionCookieSecure(),
    path: '/',
    maxAge: 0,
  });
}

/**
 * Read the JWT from either the Authorization header (Bearer …) or the
 * session cookie. Header wins — useful for direct API calls without UI.
 */
export function extractToken(req: NextRequest): string | undefined {
  const authHeader = req.headers.get('authorization');
  if (authHeader?.startsWith('Bearer ')) {
    return authHeader.slice(7).trim() || undefined;
  }
  return readSessionCookie(req);
}
