import type { AbsenceType } from './dto/absence-type'
import { extractItems } from '~/utils/api'

export const listAbsenceTypes = async () => {
  const api = useApi()
  const data = await api.get<AbsenceType[] | { 'hydra:member'?: AbsenceType[] }>(
    '/absence_types',
    {},
    { toast: false }
  )
  return extractItems<AbsenceType>(data)
}

export const createAbsenceType = async (
  payload: Pick<AbsenceType, 'code' | 'label' | 'color' | 'countAsWorkedHours'>
) => {
  const api = useApi()
  return api.post<AbsenceType>('/absence_types', payload, {
    toastSuccessKey: 'success.absenceType.create',
    toastErrorKey: 'errors.absenceType.create'
  })
}

export const updateAbsenceType = async (
  id: number,
  payload: Pick<AbsenceType, 'code' | 'label' | 'color' | 'countAsWorkedHours'>
) => {
  const api = useApi()
  return api.patch<AbsenceType>(`/absence_types/${id}`, payload, {
    toastSuccessKey: 'success.absenceType.update',
    toastErrorKey: 'errors.absenceType.update'
  })
}

export const deleteAbsenceType = async (id: number) => {
  const api = useApi()
  return api.delete(`/absence_types/${id}`, {}, {
    toastSuccessKey: 'success.absenceType.delete',
    toastErrorKey: 'errors.absenceType.delete'
  })
}
