'use client'

import { request } from '@/utils'
import { IBaseResponse } from '@/@core/types/api'
import { IProduct } from '@/types/data/simpleProduct/product.interface'
import { useCustomMutation } from '@/hooks/api'

export interface AddProductPayload {
  category_id: string
  sku: string
  name_ar: string
  name_en: string
  description_ar: string
  description_en: string
  price: string
  discount_price?: string
  is_featured: boolean
  is_available: boolean
  preparation_time?: number
  calories?: number
  sort_order?: number
  image?: File
  images?: File[]
}

export const useAddProduct = () => {
  return useCustomMutation<AddProductPayload, IBaseResponse<IProduct>>(
    ['products-add'],
    async (variables: AddProductPayload) => {
      console.log('dY"? useAddProduct received:', variables)

      const formData = new FormData()

      Object.entries(variables).forEach(([key, value]) => {
        if (value === undefined || value === null) return

        if (key === 'images' && Array.isArray(value)) {
          value.forEach(file => formData.append('images[]', file))
        } else if (key === 'image' && value instanceof File) {
          formData.append('image', value)
        } else {
          formData.append(key, String(value))
        }
      })

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

      console.log('?o. Server Response:', res)
      return res
    },
    {
      invalidateQueries: ['simple-products-list']
    }
  )
}
