// کلاینتِ APIِ پنل. احرازِ هویت با Basic Auth (همان کاربر/پسوردِ پنل ادمین) // که پس از ورود در localStorage نگه‌داری می‌شود و در هر درخواست فرستاده می‌شود. // همان مبدأ (nginx، /admin/api → بک‌اند). برای توسعه‌ی محلی با // NEXT_PUBLIC_API_URL قابلِ override است. const BASE = process.env.NEXT_PUBLIC_API_URL || "https://hakem.approagency.ir/admin/api"; // مبدأِ فایل‌های استاتیک (کارت/فرش): همان دامنه بدونِ /admin/api. export const ASSET_BASE = BASE.replace(/\/admin\/api\/?$/, ""); const AUTH_KEY = "hakem_admin_auth"; export function saveAuth(user: string, pass: string) { if (typeof window !== "undefined") { localStorage.setItem(AUTH_KEY, btoa(`${user}:${pass}`)); } } export function clearAuth() { if (typeof window !== "undefined") localStorage.removeItem(AUTH_KEY); } export function getAuth(): string | null { if (typeof window === "undefined") return null; return localStorage.getItem(AUTH_KEY); } export function isAuthed(): boolean { return !!getAuth(); } class ApiError extends Error { status: number; constructor(status: number, msg: string) { super(msg); this.status = status; } } async function request( method: string, path: string, body?: unknown, ): Promise { const auth = getAuth(); const headers: Record = { Accept: "application/json" }; if (auth) headers["Authorization"] = `Basic ${auth}`; const opts: RequestInit = { method, headers }; if (body !== undefined) { if (body instanceof FormData) { opts.body = body; } else { headers["Content-Type"] = "application/json"; opts.body = JSON.stringify(body); } } const res = await fetch(`${BASE}${path}`, opts); if (res.status === 401) { clearAuth(); if (typeof window !== "undefined") window.location.href = "/panel/login/"; throw new ApiError(401, "unauthorized"); } if (!res.ok) { const e = await res.json().catch(() => ({})); throw new ApiError(res.status, (e as { error?: string }).error || "خطا"); } return res.json() as Promise; } export const api = { get: (p: string) => request("GET", p), post: (p: string, body?: unknown) => request("POST", p, body), put: (p: string, body?: unknown) => request("PUT", p, body), del: (p: string) => request("DELETE", p), // ورود: اعتبارسنجی با فراخوانی /me. async login(user: string, pass: string) { const prev = getAuth(); saveAuth(user, pass); try { await request("GET", "/me"); return true; } catch { if (prev) localStorage.setItem(AUTH_KEY, prev); else clearAuth(); return false; } }, };