'use client'

import { request } from '@/utils'
import { IBaseResponse } from '@/@core/types/api'
import { ICategory } from '@/types/data/categories/category.interface'
import { ICreateCategoryDto } from '@/types/data/categories/category-create.interface'
import { useCustomMutation } from '@/hooks/api'

export const useAddCategory = () => {
  return useCustomMutation<ICreateCategoryDto, IBaseResponse<ICategory>>(
    ['categories-add'],
    async payload => {
      let imageValue = payload.image ?? null
      if (typeof FileList !== 'undefined' && imageValue instanceof FileList) {
        imageValue = imageValue.item(0)
      }

      const formData = new FormData()
      formData.append('name_ar', payload.name_ar)
      formData.append('name_en', payload.name_en)
      formData.append('description_ar', payload.description_ar || '')
      formData.append('description_en', payload.description_en || '')
      formData.append('sort_order', String(payload.sort_order))
      formData.append('is_active', String(payload.is_active))
      if (payload.parent_id) {
        formData.append('parent_id', payload.parent_id)
      }
      if (imageValue instanceof File) {
        formData.append('image', imageValue)
      } else if (typeof imageValue === 'string' && imageValue) {
        formData.append('image', imageValue)
      }

      const res = await request<IBaseResponse<ICategory>>({
        url: '/categories',
        method: 'POST',
        data: formData,
        headers: { 'Content-Type': 'multipart/form-data' }
      })

      return res
    },
    {
      invalidateQueries: ['categories-list']
    }
  )
}
