import type { Address, AddressWrite } from './dto/address'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'

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

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

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

    async function create(payload: AddressWrite): Promise<Address> {
        return api.post<Address>('/addresses', payload as Record<string, unknown>, {
            toastSuccessKey: 'directory.addresses.saved',
        })
    }

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

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

    return { getByOwner, create, update, remove }
}
