import type { Ref } from 'vue'
import type { Observation } from '~/services/dto/observation'
import type { Employee } from '~/services/dto/employee'
import {
  listObservations,
  createObservation,
  updateObservation,
  deleteObservation
} from '~/services/observations'

export const useEmployeeObservation = (employee: Ref<Employee | null>, reloadEmployee: () => Promise<void>) => {
  const observations = ref<Observation[]>([])
  const isObservationLoading = ref(false)
  const observationDataLoaded = ref(false)

  const loadObservationData = async () => {
    if (!employee.value || isObservationLoading.value) return
    isObservationLoading.value = true
    try {
      observations.value = await listObservations(employee.value.id)
      observationDataLoaded.value = true
    } finally {
      isObservationLoading.value = false
    }
  }

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

  const submitCreateObservation = async (data: { month: string; content: string }) => {
    if (!employee.value) return
    await createObservation({
      employeeId: employee.value.id,
      month: data.month,
      content: data.content
    })
    await reloadEmployee()
  }

  const submitUpdateObservation = async (id: number, data: { month: string; content: string }) => {
    await updateObservation(id, data)
    await reloadEmployee()
  }

  const submitDeleteObservation = async (id: number) => {
    await deleteObservation(id)
    await reloadEmployee()
  }

  return {
    observations,
    isObservationLoading,
    observationDataLoaded,
    loadObservationData,
    resetLoaded,
    submitCreateObservation,
    submitUpdateObservation,
    submitDeleteObservation
  }
}
