import { ApiError, request } from './client';
import type { components } from './generated/v1';

// The list endpoint (GET /api/v1/filler-presets) is picker-grade (id + name) and is already
// provided by pickers.ts as getFillerPresets(). This module adds the by-id read (full
// model) and the mutations.

export type FillerPresetDetail = components['schemas']['FillerPresetFullResponseModel'];
export type CreateFillerPresetRequest = components['schemas']['CreateFillerPresetRequest'];
export type UpdateFillerPresetRequest = components['schemas']['UpdateFillerPresetRequest'];

export function getFillerPreset(id: number): Promise<FillerPresetDetail> {
  return request<FillerPresetDetail>(`/api/v1/filler-presets/${id}`);
}

export function createFillerPreset(body: CreateFillerPresetRequest): Promise<FillerPresetDetail> {
  return request<FillerPresetDetail>('/api/v1/filler-presets', { body, method: 'POST' });
}

export function updateFillerPreset(id: number, body: UpdateFillerPresetRequest): Promise<FillerPresetDetail> {
  return request<FillerPresetDetail>(`/api/v1/filler-presets/${id}`, { body, method: 'PUT' });
}

export function deleteFillerPreset(id: number): Promise<void> {
  return request<void>(`/api/v1/filler-presets/${id}`, { method: 'DELETE' });
}

export function messageFromFillerPresetError(error: unknown, fallback = 'Unable to load filler presets'): string {
  if (error instanceof ApiError) {
    return error.detail ?? error.message;
  }

  if (error instanceof Error) {
    return error.message;
  }

  return fallback;
}
