import { $fetch } from 'ofetch'
import type { Formation } from './dto/formation'
import { extractItems } from '~/utils/api'

export const listFormations = async (employeeId: number) => {
  const api = useApi()
  const data = await api.get<Formation[] | { 'hydra:member'?: Formation[] }>(
    '/formations',
    { employee: `/api/employees/${employeeId}` },
    { toast: false }
  )
  return extractItems<Formation>(data)
}

export const listFormationsByDateRange = async (from: string, to: string) => {
  const api = useApi()
  const data = await api.get<Formation[] | { 'hydra:member'?: Formation[] }>(
    '/formations',
    {
      'startDate[before]': to,
      'endDate[after]': from
    },
    { toast: false }
  )
  return extractItems<Formation>(data)
}

export const createFormation = async (data: {
  employeeId: number
  startDate: string
  endDate: string
  comment?: string
}) => {
  const api = useApi()
  return api.post<Formation>('/formations', {
    employee: `/api/employees/${data.employeeId}`,
    startDate: data.startDate,
    endDate: data.endDate,
    comment: data.comment
  }, {
    toastSuccessKey: 'success.formation.create',
    toastErrorKey: 'errors.formation.create'
  })
}

export const updateFormation = async (id: number, data: {
  startDate: string
  endDate: string
  comment?: string
}) => {
  const api = useApi()
  return api.patch<Formation>(`/formations/${id}`, {
    startDate: data.startDate,
    endDate: data.endDate,
    comment: data.comment
  }, {
    toastSuccessKey: 'success.formation.update',
    toastErrorKey: 'errors.formation.update'
  })
}

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

export const uploadFormationJustificatif = async (baseURL: string, id: number, file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  return $fetch(`${baseURL}/formations/${id}/justificatif`, {
    method: 'POST',
    body: formData,
    credentials: 'include'
  })
}

export const getFormationJustificatifUrl = (baseURL: string, id: number): string => {
  return `${baseURL}/formations/${id}/justificatif`
}
