// 2026-11-10 — Dynamic permissions of the logged-in user.
//   getMyEffectivePermissions(): direct + ROLE permissions (GET /api/permissions/me/effective).
//     The Companies / Job Registrar tables used to read only direct user permissions
//     (/user-permissions/user/:id); they now also merge rolePermissions, so a role such as
//     "Job Documents" works on screen as it already did on the server.
//   getJobDocsAccess(): { view, stages } for Create Job / View Jobs & Documents
//     (GET /api/company-documents/access — admin/scheme/coordinator keep full access).
import { fetchApi, API_BASE_URL } from "@/lib/api/http";

export interface MyEffectivePermissions {
  roles: string[];
  modules: Record<string, string[]>;
  rolePermissions: any[];
}
export type JobDocsStage = "Stage 1" | "Stage 2";
export interface JobDocsAccess {
  view: boolean;
  stages: JobDocsStage[];
  source?: string;
}

let effCache: { at: number; p: Promise<MyEffectivePermissions | null> } | null = null;
let accCache: { at: number; p: Promise<JobDocsAccess> } | null = null;
const TTL = 60_000;

export function getMyEffectivePermissions(force = false): Promise<MyEffectivePermissions | null> {
  if (!force && effCache && Date.now() - effCache.at < TTL) return effCache.p;
  const p = fetchApi<MyEffectivePermissions>(`${API_BASE_URL}/permissions/me/effective`).catch(() => null);
  effCache = { at: Date.now(), p };
  return p;
}

/** role permissions in the same shape as /user-permissions/user/:id rows ([] on any error) */
export async function getMyRolePermissionRows(): Promise<any[]> {
  const eff = await getMyEffectivePermissions(true);
  return Array.isArray(eff?.rolePermissions) ? eff!.rolePermissions : [];
}

export function getJobDocsAccess(force = false): Promise<JobDocsAccess> {
  if (!force && accCache && Date.now() - accCache.at < TTL) return accCache.p;
  const p = fetchApi<JobDocsAccess>(`${API_BASE_URL}/company-documents/access`)
    .then((r) => ({ view: !!r?.view, stages: Array.isArray(r?.stages) ? r.stages : [], source: r?.source }))
    .catch(() => ({ view: false, stages: [] as JobDocsStage[] }));
  accCache = { at: Date.now(), p };
  return p;
}
