"use client";

/** Browser-side API helpers: relative URLs (proxied by Next) + CSRF double-submit header. */

function readCookie(name: string): string | null {
  const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
  return match ? decodeURIComponent(match[1] as string) : null;
}

export interface ApiResult<T> {
  status: number;
  data: T | null;
  error: string | null;
}

export async function api<T>(path: string, method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" = "GET", body?: unknown): Promise<ApiResult<T>> {
  const headers: Record<string, string> = { "Content-Type": "application/json" };
  if (method !== "GET") {
    const csrf = readCookie("bousla_csrf");
    if (csrf) headers["x-csrf-token"] = csrf;
  }
  try {
    const res = await fetch(path, {
      method,
      headers,
      credentials: "same-origin",
      body: body === undefined ? undefined : JSON.stringify(body),
    });
    let data: T | null = null;
    try {
      data = (await res.json()) as T;
    } catch {
      /* empty body */
    }
    const error = data && typeof data === "object" && "error" in data ? String((data as { error: unknown }).error) : null;
    return { status: res.status, data, error };
  } catch {
    return { status: 0, data: null, error: "تعذر الاتصال بالخادم" };
  }
}

/** Ensure a CSRF cookie exists (issued by the API); returns the token for direct use. */
export async function ensureCsrf(): Promise<string | null> {
  const existing = readCookie("bousla_csrf");
  if (existing) return existing;
  const res = await fetch("/api/auth/csrf", { credentials: "same-origin" });
  if (!res.ok) return null;
  const data = (await res.json()) as { csrfToken?: string };
  return data.csrfToken ?? readCookie("bousla_csrf");
}
