const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8000/api";

export type ApiUser = {
  id: number;
  name: string;
  email: string;
  branch_id: number | null;
  branch?: { id: number; name: string } | null;
  reporting_to: number | null;
  role: string | null;
  role_label?: string;
  capabilities: {
    can_filter_branch: boolean;
    can_filter_team_leader: boolean;
    can_filter_sales_person: boolean;
    allowed_branch_ids: number[];
  };
  headed_branches: { id: number; name: string }[];
  /** Granted permission slugs (super-admin gets all). */
  permissions?: string[];
  /** When true, sidebar uses permissions instead of role-only fallback. */
  permissions_locked?: boolean;
};

type ApiOptions = {
  method?: string;
  body?: unknown;
  token?: string | null;
  params?: Record<string, string | number | boolean | Array<string | number> | undefined | null>;
};

function buildUrl(path: string, params?: ApiOptions["params"]) {
  const url = new URL(path.startsWith("http") ? path : `${API_URL}${path.startsWith("/") ? path : `/${path}`}`);
  if (params) {
    Object.entries(params).forEach(([key, value]) => {
      if (value === undefined || value === null || value === "") return;
      if (Array.isArray(value)) {
        value.forEach((v) => url.searchParams.append(`${key}[]`, String(v)));
      } else {
        url.searchParams.set(key, String(value));
      }
    });
  }
  return url.toString();
}

export async function api<T = unknown>(path: string, options: ApiOptions = {}): Promise<T> {
  const token = options.token ?? (typeof window !== "undefined" ? localStorage.getItem("ps_token") : null);
  const res = await fetch(buildUrl(path, options.params), {
    method: options.method || "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    body: options.body ? JSON.stringify(options.body) : undefined,
    cache: "no-store",
  });

  const json = await res.json().catch(() => ({}));
  if (!res.ok) {
    const message = json?.message || json?.errors || `Request failed (${res.status})`;
    throw new Error(typeof message === "string" ? message : JSON.stringify(message));
  }
  return json as T;
}
