import { useAuthStore } from "../store/auth"; const BASE = "/api"; async function request( url: string, options: RequestInit = {}, withAuth = true ): Promise { const headers: Record = { "Content-Type": "application/json", ...(options.headers as Record), }; if (withAuth) { const token = useAuthStore.getState().accessToken; if (token) headers["Authorization"] = `Bearer ${token}`; } const res = await fetch(`${BASE}${url}`, { ...options, headers }); if (res.status === 401 && withAuth) { const refreshToken = useAuthStore.getState().refreshToken; if (refreshToken) { const refreshRes = await fetch(`${BASE}/web/refresh`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ refresh_token: refreshToken }), }); if (refreshRes.ok) { const data = await refreshRes.json(); if (data.ok) { useAuthStore.getState().setAuth( data.access_token, data.refresh_token, useAuthStore.getState().user! ); headers["Authorization"] = `Bearer ${data.access_token}`; const retryRes = await fetch(`${BASE}${url}`, { ...options, headers }); return retryRes.json(); } } } useAuthStore.getState().logout(); window.location.href = "/login"; return { ok: false, error: "Session expired" }; } return res.json(); } export const api = { register: (email: string, password: string, name?: string) => request("/web/register", { method: "POST", body: JSON.stringify({ email, password, name }), }, false), login: (email: string, password: string) => request("/web/login", { method: "POST", body: JSON.stringify({ email, password }), }, false), tgAuth: (data: Record) => request("/web/tg_auth", { method: "POST", body: JSON.stringify(data), }, false), refresh: (refresh_token: string) => request("/web/refresh", { method: "POST", body: JSON.stringify({ refresh_token }), }, false), action: (action: string, payload: Record = {}) => request("/web/action", { method: "POST", body: JSON.stringify({ action, payload }), }), };