import type { Ref } from 'vue'
import type { Bonus } from '~/services/dto/bonus'
import type { Employee } from '~/services/dto/employee'
import {
  listBonuses,
  createBonus,
  updateBonus,
  deleteBonus
} from '~/services/bonuses'

export const useEmployeeBonus = (employee: Ref<Employee | null>, reloadEmployee: () => Promise<void>) => {
  const bonuses = ref<Bonus[]>([])
  const isBonusLoading = ref(false)
  const bonusDataLoaded = ref(false)

  const loadBonusData = async () => {
    if (!employee.value || isBonusLoading.value) return
    isBonusLoading.value = true
    try {
      bonuses.value = await listBonuses(employee.value.id)
      bonusDataLoaded.value = true
    } finally {
      isBonusLoading.value = false
    }
  }

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

  const submitCreateBonus = async (data: { month: string; amount: number; comment?: string }) => {
    if (!employee.value) return
    await createBonus({
      employeeId: employee.value.id,
      month: data.month,
      amount: data.amount,
      comment: data.comment
    })
    await reloadEmployee()
  }

  const submitUpdateBonus = async (id: number, data: { month: string; amount: number; comment?: string }) => {
    await updateBonus(id, data)
    await reloadEmployee()
  }

  const submitDeleteBonus = async (id: number) => {
    await deleteBonus(id)
    await reloadEmployee()
  }

  return {
    bonuses,
    isBonusLoading,
    bonusDataLoaded,
    loadBonusData,
    resetLoaded,
    submitCreateBonus,
    submitUpdateBonus,
    submitDeleteBonus
  }
}
