// frontend/lib/session.js
import { cookies } from "next/headers";

const COOKIE_NAME = "access_token";
const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";

/**
 * Server-side function to get the current session from the request cookies.
 * This can only be used in Server Components, Server Actions, or Route Handlers.
 */
export async function getSession() {
  const cookieStore = cookies();
  const token = cookieStore.get(COOKIE_NAME)?.value;

  if (!token) return null;

  try {
    const res = await fetch(`${API_BASE}/api/auth/me`, {
      headers: { Authorization: `Bearer ${token}` },
      cache: "no-store",
    });

    if (!res.ok) return null;
    
    const data = await res.json();
    return data; // Expects { user, permissions, ... }
  } catch (error) {
    console.error("Error fetching session:", error);
    return null;
  }
}