import { apiGet, apiPost, apiPatch } from './client' import type { AreaCreate, AreaListResponse, AreaRead, MunicipalitySearchResponse } from '../../types' const AREA_PAGE_SIZE = 200 async function listProjectAreas(projectId: string): Promise { const items: AreaRead[] = [] let offset = 0 let total: number | null = null do { const page = await apiGet( `/api/v1/projects/${projectId}/areas?limit=${AREA_PAGE_SIZE}&offset=${offset}`, ) if (total === null) { total = page.total } else if (page.total !== total) { throw new Error('De gebiedslijst wijzigde tijdens het laden. Vernieuw de werkruimte.') } items.push(...page.items) if (page.items.length === 0) { break } offset += page.items.length } while (offset < (total ?? 0)) if (total !== null && items.length !== total) { throw new Error(`Niet alle gebieden konden worden geladen (${items.length}/${total}).`) } return { items, total: total ?? 0, limit: items.length, offset: 0 } } export const areasApi = { list: listProjectAreas, create: (projectId: string, payload: AreaCreate): Promise => apiPost(`/api/v1/projects/${projectId}/areas`, payload), get: (projectId: string, areaId: string): Promise => apiGet(`/api/v1/projects/${projectId}/areas/${areaId}`), update: (projectId: string, areaId: string, payload: Partial): Promise => apiPatch(`/api/v1/projects/${projectId}/areas/${areaId}`, payload), searchMunicipalities: (projectId: string, query: string): Promise => apiGet(`/api/v1/projects/${projectId}/areas/municipalities?query=${encodeURIComponent(query)}&limit=12`), activateMunicipality: (projectId: string, niscode: string): Promise => apiPost(`/api/v1/projects/${projectId}/areas/municipalities/${encodeURIComponent(niscode)}/activate`, {}), }