import type { IngestionJobStatus, CompletePayload, CompleteResponse, LeaderboardEntry, FeedEntry, } from '@/types' const INGESTION_URL = process.env.NEXT_PUBLIC_INGESTION_URL ?? 'http://localhost:3001' const GENERATION_URL = process.env.NEXT_PUBLIC_GENERATION_URL ?? 'http://localhost:3002' const CURRICULUM_URL = process.env.NEXT_PUBLIC_CURRICULUM_URL ?? 'http://localhost:3003' const PROGRESS_URL = process.env.NEXT_PUBLIC_PROGRESS_URL ?? 'http://localhost:3005' async function handleResponse(res: Response): Promise { if (!res.ok) { const text = await res.text().catch(() => res.statusText) throw new Error(`HTTP ${res.status}: ${text}`) } return res.json() as Promise } export async function postIngest(payload: { documentId: string filename: string format: 'pdf' | 'md' | 'txt' fileUrl: string }): Promise<{ jobId: string }> { const res = await fetch(`${INGESTION_URL}/ingest`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }) return handleResponse<{ jobId: string }>(res) } export async function getIngestionStatus(jobId: string): Promise { const res = await fetch(`${INGESTION_URL}/ingest/status/${encodeURIComponent(jobId)}`) return handleResponse(res) } export async function postGenerateAll(themeId: string): Promise<{ queued: number }> { const res = await fetch(`${GENERATION_URL}/generate/theme/${encodeURIComponent(themeId)}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, }) return handleResponse<{ queued: number }>(res) } export async function postComplete(payload: CompletePayload): Promise { const res = await fetch(`${PROGRESS_URL}/complete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }) return handleResponse(res) } export async function getLeaderboard(): Promise { const res = await fetch(`${PROGRESS_URL}/leaderboard`) return handleResponse(res) } export async function getFeed(): Promise { const res = await fetch(`${PROGRESS_URL}/feed`) return handleResponse(res) } export async function postCurriculumConfirm(versionId: string): Promise { const res = await fetch( `${CURRICULUM_URL}/curriculum/versions/${encodeURIComponent(versionId)}/confirm`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, }, ) if (!res.ok) { const text = await res.text().catch(() => res.statusText) throw new Error(`HTTP ${res.status}: ${text}`) } } export async function patchCurriculumWeekOrder(weekId: string, position: number): Promise { const res = await fetch( `${CURRICULUM_URL}/curriculum/weeks/${encodeURIComponent(weekId)}/order`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ position }), }, ) if (!res.ok) { const text = await res.text().catch(() => res.statusText) throw new Error(`HTTP ${res.status}: ${text}`) } }