import type { Ref } from 'vue'
import type { MileageAllowance } from '~/services/dto/mileage-allowance'
import type { Employee } from '~/services/dto/employee'
import {
  listMileageAllowances,
  createMileageAllowance,
  updateMileageAllowance,
  deleteMileageAllowance,
  uploadKmReceipt,
  uploadAmountReceipt
} from '~/services/mileage-allowances'

export const useEmployeeMileage = (employee: Ref<Employee | null>, reloadEmployee: () => Promise<void>) => {
  const config = useRuntimeConfig()
  const apiBase = (config.public.apiBase as string) ?? '/api'

  const mileageAllowances = ref<MileageAllowance[]>([])
  const isMileageLoading = ref(false)
  const mileageDataLoaded = ref(false)

  const loadMileageData = async () => {
    if (!employee.value || isMileageLoading.value) return
    isMileageLoading.value = true
    try {
      mileageAllowances.value = await listMileageAllowances(employee.value.id)
      mileageDataLoaded.value = true
    } finally {
      isMileageLoading.value = false
    }
  }

  const resetLoaded = () => {
    mileageDataLoaded.value = false
  }

  const submitCreateMileage = async (data: { month: string; kilometers: number; amount: number; comment?: string }, kmFile?: File, amountFile?: File) => {
    if (!employee.value) return
    const result = await createMileageAllowance({
      employeeId: employee.value.id,
      month: data.month,
      kilometers: data.kilometers,
      amount: data.amount,
      comment: data.comment
    })
    if (result?.id) {
      if (kmFile) {
        await uploadKmReceipt(apiBase, result.id, kmFile)
      }
      if (amountFile) {
        await uploadAmountReceipt(apiBase, result.id, amountFile)
      }
    }
    await reloadEmployee()
  }

  const submitUpdateMileage = async (id: number, data: { month: string; kilometers: number; amount: number; comment?: string }, kmFile?: File, amountFile?: File) => {
    await updateMileageAllowance(id, data)
    if (kmFile) {
      await uploadKmReceipt(apiBase, id, kmFile)
    }
    if (amountFile) {
      await uploadAmountReceipt(apiBase, id, amountFile)
    }
    await reloadEmployee()
  }

  const submitDeleteMileage = async (id: number) => {
    await deleteMileageAllowance(id)
    await reloadEmployee()
  }

  return {
    mileageAllowances,
    isMileageLoading,
    mileageDataLoaded,
    mileageApiBase: apiBase,
    loadMileageData,
    resetLoaded,
    submitCreateMileage,
    submitUpdateMileage,
    submitDeleteMileage
  }
}
