import { $fetch } from 'ofetch'
import type { MileageAllowance } from './dto/mileage-allowance'
import { extractItems } from '~/utils/api'

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

export const createMileageAllowance = async (data: {
  employeeId: number
  month: string
  kilometers: number
  amount: number
  comment?: string
}) => {
  const api = useApi()
  return api.post<MileageAllowance>('/mileage_allowances', {
    employee: `/api/employees/${data.employeeId}`,
    month: data.month,
    kilometers: data.kilometers,
    amount: data.amount,
    comment: data.comment
  }, {
    toastSuccessKey: 'success.mileage.create',
    toastErrorKey: 'errors.mileage.create'
  })
}

export const updateMileageAllowance = async (id: number, data: {
  month: string
  kilometers: number
  amount: number
  comment?: string
}) => {
  const api = useApi()
  return api.patch<MileageAllowance>(`/mileage_allowances/${id}`, {
    month: data.month,
    kilometers: data.kilometers,
    amount: data.amount,
    comment: data.comment
  }, {
    toastSuccessKey: 'success.mileage.update',
    toastErrorKey: 'errors.mileage.update'
  })
}

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

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

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

export const getKmReceiptUrl = (baseURL: string, id: number): string => {
  return `${baseURL}/mileage_allowances/${id}/receipt`
}

export const getAmountReceiptUrl = (baseURL: string, id: number): string => {
  return `${baseURL}/mileage_allowances/${id}/amount-receipt`
}
