import type { Prospect, ProspectStatus, ProspectWrite } from './dto/prospect'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'

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

    async function getAll(status?: ProspectStatus): Promise<Prospect[]> {
        const query: Record<string, unknown> = {}
        if (status) query.status = status
        const data = await api.get<HydraCollection<Prospect>>('/prospects', query)
        return extractHydraMembers(data)
    }

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

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

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

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

    async function convert(id: number): Promise<Prospect> {
        return api.post<Prospect>(`/prospects/${id}/convert`, {}, {
            toastSuccessKey: 'prospects.converted',
        })
    }

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