// lib/api/platforms.ts export type Platform = { id: number; key: string; label: string; isActive: boolean; }; export type CreatePlatformDto = { key: string; label: string; isActive?: boolean; }; export type UpdatePlatformDto = Partial; const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL ?? ""; function normalizePlatform(raw: any): Platform { const id = Number(raw?.id); const key = String(raw?.key ?? "").trim(); const label = String(raw?.label ?? "").trim(); const activeRaw = raw?.isActive ?? raw?.is_active ?? true; const isActive = typeof activeRaw === "boolean" ? activeRaw : typeof activeRaw === "number" ? activeRaw === 1 : String(activeRaw).toLowerCase() === "true"; return { id, key, label, isActive }; } export async function fetchPlatforms(tokenHeaders: HeadersInit): Promise { const res = await fetch(`${API_BASE}/api/platforms`, { headers: { ...tokenHeaders }, }); if (!res.ok) { throw new Error(`Failed to load platforms (${res.status})`); } const data = (await res.json()) as unknown; const items = Array.isArray(data) ? data : []; return items.map(normalizePlatform).filter((p) => Number.isFinite(p.id) && p.key && p.label); } export async function createPlatform( tokenHeaders: HeadersInit, dto: CreatePlatformDto ): Promise { const res = await fetch(`${API_BASE}/api/platforms`, { method: "POST", headers: { "Content-Type": "application/json", ...tokenHeaders, }, body: JSON.stringify(dto), }); if (!res.ok) { const text = await res.text().catch(() => ""); throw new Error(text || `Failed to create platform (${res.status})`); } return normalizePlatform(await res.json()); } export async function updatePlatform( tokenHeaders: HeadersInit, id: number, dto: UpdatePlatformDto ): Promise { const res = await fetch(`${API_BASE}/api/platforms/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json", ...tokenHeaders, }, body: JSON.stringify({ isActive: dto.isActive }), }); if (!res.ok) { const text = await res.text().catch(() => ""); throw new Error(text || `Failed to update platform (${res.status})`); } return normalizePlatform(await res.json()); } export async function deletePlatform(tokenHeaders: HeadersInit, id: number): Promise { const res = await fetch(`${API_BASE}/api/platforms/${id}`, { method: "DELETE", headers: { ...tokenHeaders }, }); if (!res.ok) { const text = await res.text().catch(() => ""); throw new Error(text || `Failed to delete platform (${res.status})`); } }