import type { Absence } from './dto/absence'
import type { HalfDay } from './dto/half-day'
import { extractItems } from '~/utils/api'

type ListAbsencesFilters = {
  from?: string
  to?: string
  siteIds?: number[]
  employeeId?: number
}

export const listAbsences = async (filters: ListAbsencesFilters = {}) => {
  const api = useApi()
  const query: Record<string, string | string[]> = {}
  if (filters.from) {
    query['endDate[after]'] = filters.from
  }
  if (filters.to) {
    query['startDate[before]'] = filters.to
  }
  if (filters.siteIds && filters.siteIds.length > 0) {
    query['employee.site[]'] = filters.siteIds.map((id) => `/api/sites/${id}`)
  }
  if (filters.employeeId) {
    query.employee = `/api/employees/${filters.employeeId}`
  }
  const data = await api.get<Absence[] | { 'hydra:member'?: Absence[] }>(
    '/absences',
    query,
    { toast: false }
  )
  return extractItems<Absence>(data)
}

export const createAbsence = async (payload: {
  employeeId: number
  typeId: number
  startDate: string
  startHalf: HalfDay
  endDate: string
  endHalf: HalfDay
  comment?: string
}) => {
  const api = useApi()
  return api.post<Absence>('/absences', {
    employee: `/api/employees/${payload.employeeId}`,
    type: `/api/absence_types/${payload.typeId}`,
    startDate: payload.startDate,
    startHalf: payload.startHalf,
    endDate: payload.endDate,
    endHalf: payload.endHalf,
    comment: payload.comment
  }, {
    toastSuccessKey: 'success.absence.create',
    toastErrorKey: 'errors.absence.create'
  })
}

export const updateAbsence = async (payload: {
  id: number
  employeeId: number
  typeId: number
  startDate: string
  startHalf: HalfDay
  endDate: string
  endHalf: HalfDay
  comment?: string
}) => {
  const api = useApi()
  return api.patch<Absence>(`/absences/${payload.id}`, {
    employee: `/api/employees/${payload.employeeId}`,
    type: `/api/absence_types/${payload.typeId}`,
    startDate: payload.startDate,
    startHalf: payload.startHalf,
    endDate: payload.endDate,
    endHalf: payload.endHalf,
    comment: payload.comment
  }, {
    toastSuccessKey: 'success.absence.update',
    toastErrorKey: 'errors.absence.update'
  })
}

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