import type { CommercialReport, CommercialReportWrite } from './dto/commercial-report'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'

type Owner = { client?: string, prospect?: string, prestataire?: string }

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

    async function getByOwner(owner: Owner): Promise<CommercialReport[]> {
        const data = await api.get<HydraCollection<CommercialReport>>('/commercial_reports', owner as Record<string, unknown>)
        return extractHydraMembers(data)
    }

    async function create(payload: CommercialReportWrite): Promise<CommercialReport> {
        return api.post<CommercialReport>('/commercial_reports', payload as Record<string, unknown>, {
            toastSuccessKey: 'directory.reports.saved',
        })
    }

    async function update(id: number, payload: Partial<CommercialReportWrite>): Promise<CommercialReport> {
        return api.patch<CommercialReport>(`/commercial_reports/${id}`, payload as Record<string, unknown>, {
            toastSuccessKey: 'directory.reports.saved',
        })
    }

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

    return { getByOwner, create, update, remove }
}
