import { cookies, headers } from "next/headers";

const API_URL = process.env.API_URL ?? "http://127.0.0.1:4000";

export interface CurrentUser {
  id: number;
  username: string;
  fullName: string;
  email: string | null;
  mustChangePassword: boolean;
  isDemo: boolean;
  roles: { code: string; nameAr: string; governorateIds: number[] }[];
  permissions: string[];
  preferences: { locale: "ar" | "en" | null; theme: "light" | "dark" | null };
  hasMemberFile: boolean;
}

/** Server-side fetch that forwards the browser session cookie to the API. */
export async function apiFetch<T>(path: string, init: RequestInit = {}): Promise<{ status: number; data: T | null }> {
  const cookieHeader = (await headers()).get("cookie") ?? "";
  const res = await fetch(`${API_URL}${path}`, {
    ...init,
    headers: {
      "Content-Type": "application/json",
      "User-Agent": (await headers()).get("user-agent") ?? "bousla-web-ssr",
      Cookie: cookieHeader,
      ...(init.headers ?? {}),
    },
    cache: "no-store",
  });
  let data: T | null = null;
  try {
    data = (await res.json()) as T;
  } catch {
    /* empty body */
  }
  return { status: res.status, data };
}

export async function getCurrentUser(): Promise<CurrentUser | null> {
  const { status, data } = await apiFetch<{ user: CurrentUser }>("/api/auth/me");
  if (status !== 200 || !data?.user) return null;
  return data.user;
}

export { cookies };
