import type { Client, ClientWrite } from './dto/client'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'

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

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

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

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

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

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

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