import type { Ref } from 'vue'
import type { Formation } from '~/services/dto/formation'
import type { Employee } from '~/services/dto/employee'
import {
  listFormations,
  createFormation,
  updateFormation,
  deleteFormation,
  uploadFormationJustificatif
} from '~/services/formations'

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

  const formations = ref<Formation[]>([])
  const isFormationLoading = ref(false)
  const formationDataLoaded = ref(false)

  const loadFormationData = async () => {
    if (!employee.value || isFormationLoading.value) return
    isFormationLoading.value = true
    try {
      formations.value = await listFormations(employee.value.id)
      formationDataLoaded.value = true
    } finally {
      isFormationLoading.value = false
    }
  }

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

  const submitCreateFormation = async (data: { startDate: string; endDate: string; comment?: string }, justificatifFile?: File) => {
    if (!employee.value) return
    const result = await createFormation({
      employeeId: employee.value.id,
      startDate: data.startDate,
      endDate: data.endDate,
      comment: data.comment
    })
    if (result?.id && justificatifFile) {
      await uploadFormationJustificatif(apiBase, result.id, justificatifFile)
    }
    await reloadEmployee()
  }

  const submitUpdateFormation = async (id: number, data: { startDate: string; endDate: string; comment?: string }, justificatifFile?: File) => {
    await updateFormation(id, data)
    if (justificatifFile) {
      await uploadFormationJustificatif(apiBase, id, justificatifFile)
    }
    await reloadEmployee()
  }

  const submitDeleteFormation = async (id: number) => {
    await deleteFormation(id)
    await reloadEmployee()
  }

  return {
    formations,
    isFormationLoading,
    formationDataLoaded,
    formationApiBase: apiBase,
    loadFormationData,
    resetLoaded,
    submitCreateFormation,
    submitUpdateFormation,
    submitDeleteFormation
  }
}
