import { clientFetch } from '@/lib/api/client';
import { unwrap, type ApiEnvelope, type Paginated } from '@/lib/api/types';
import { SERVICE_AREAS_PAGE_SIZE } from '../constants';
import type { AddServiceAreaInput, NurseServiceArea, ServiceAreasApi } from '../types';

const BASE = '/api/v1/nurse_service_areas';

/**
 * Real HTTP implementation of the ServiceAreasApi seam (b4 action-style routes). A duplicate
 * `add` returns `409` — `clientFetch` throws `ApiError(409)` (no toast; "other 4xx"), which the
 * add hook/screen maps to the inline "already covered" message. Selected once
 * USE_SERVICE_AREAS_MOCK is false.
 */
export const serviceAreasClientApi: ServiceAreasApi = {
  list: async (params) => {
    const query = new URLSearchParams();
    query.set('page', String(params?.page ?? 1));
    // Pagination binds case-insensitively to the server's `PageSize` (not snake_cased); match the template.
    query.set('pageSize', String(params?.pageSize ?? SERVICE_AREAS_PAGE_SIZE));
    return unwrap(
      await clientFetch<ApiEnvelope<Paginated<NurseServiceArea>>>(`${BASE}/list?${query.toString()}`),
    );
  },

  add: async (input: AddServiceAreaInput) =>
    unwrap(
      await clientFetch<ApiEnvelope<NurseServiceArea>>(`${BASE}/add`, {
        method: 'POST',
        body: JSON.stringify({ cityId: input.cityId, districtId: input.districtId ?? null }),
      }),
    ),

  remove: async (id: number) => {
    await clientFetch<ApiEnvelope<boolean>>(`${BASE}/remove/${id}`, { method: 'DELETE' });
  },
};
