export const API_BASE = '/api/proxy/v1/admin-console/kcgm';
export function getToken(): string | null { return typeof window !== 'undefined' ? localStorage.getItem('kcgm_token') : null; }
export function setToken(t: string | null) { if (typeof window === 'undefined') return; if (t) localStorage.setItem('kcgm_token', t); else localStorage.removeItem('kcgm_token'); }

/** GET and unwrap the { data } envelope. */
export async function apiGet<T = any>(path: string): Promise<T> {
  const t = getToken();
  const r = await fetch(API_BASE + path, { headers: t ? { Authorization: 'Bearer ' + t } : {} });
  const j = await r.json().catch(() => ({}));
  return (j && typeof j === 'object' && 'data' in j ? (j as any).data : j) as T;
}
/** POST and return the raw envelope ({ data } or { error }) plus status. */
export async function apiPost(path: string, body: any): Promise<{ status: number; json: any }> {
  const t = getToken();
  const r = await fetch(API_BASE + path, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', ...(t ? { Authorization: 'Bearer ' + t } : {}) },
    body: JSON.stringify(body),
  });
  return { status: r.status, json: await r.json().catch(() => ({})) };
}
