import { getSession } from "next-auth/react"; import { Category, CategoryListResponse } from "../types/category"; const API_URL = process.env.NEXT_PUBLIC_API_URL + "/api/v1"; async function fetchWithAuth(url: string, options: RequestInit = {}) { const session = await getSession(); if (!session?.accessToken) { throw new Error("No access token found"); } const headers = { ...options.headers, "Authorization": `Bearer ${session.accessToken}`, "Content-Type": "application/json", }; const response = await fetch(url, { ...options, headers }); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.error || errorData.message || "API request failed"); } // For 204 No Content if (response.status === 204) { return null; } return response.json(); } export const categoryService = { async getCategories(page = 1, perPage = 20, search = "", soft = ""): Promise { const query = new URLSearchParams({ page: page.toString(), per_page: perPage.toString(), q: search, soft: soft, }); const data = await fetchWithAuth(`${API_URL}/admin/categories?${query}`); return data; }, async createCategory(data: Partial): Promise { const res = await fetchWithAuth(`${API_URL}/admin/categories`, { method: "POST", body: JSON.stringify(data), }); return res.data; }, async updateCategory(id: number, data: Partial): Promise { const res = await fetchWithAuth(`${API_URL}/admin/categories/${id}`, { method: "PUT", body: JSON.stringify(data), }); return res.data; }, async deleteCategory(id: number): Promise { await fetchWithAuth(`${API_URL}/admin/categories/${id}`, { method: "DELETE", }); }, async restoreCategory(id: number): Promise { const res = await fetchWithAuth(`${API_URL}/admin/categories/${id}/restore`, { method: "POST", body: JSON.stringify({}), }); return res.data; } };