import type { Prestataire, PrestataireWrite } from './dto/prestataire'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'

export function usePrestataireService() {
    const api = useApi()

    async function getAll(): Promise<Prestataire[]> {
        const data = await api.get<HydraCollection<Prestataire>>('/prestataires')
        return extractHydraMembers(data)
    }

    async function getById(id: number): Promise<Prestataire> {
        return api.get<Prestataire>(`/prestataires/${id}`)
    }

    async function create(payload: PrestataireWrite): Promise<Prestataire> {
        return api.post<Prestataire>('/prestataires', payload as Record<string, unknown>, {
            toastSuccessKey: 'prestataires.created',
        })
    }

    async function update(id: number, payload: Partial<PrestataireWrite>): Promise<Prestataire> {
        return api.patch<Prestataire>(`/prestataires/${id}`, payload as Record<string, unknown>, {
            toastSuccessKey: 'prestataires.updated',
        })
    }

    async function remove(id: number): Promise<void> {
        await api.delete(`/prestataires/${id}`, {}, {
            toastSuccessKey: 'prestataires.deleted',
        })
    }

    return { getAll, getById, create, update, remove }
}
