'use client'

import { useQuery } from '@tanstack/react-query'
import { request } from '@/utils'

import { IBaseResponse } from '@/@core/types/api'
import { IProduct } from '@/types/data/simpleProduct/product.interface'
import { revalidatePath } from 'next/cache'
import { useCustomMutation } from '@/hooks/api'
export const PRODUCT_QUERY_KEY = 'product'

export const useGetProduct = (id?: string) => {
  return useQuery<IBaseResponse<IProduct>>({
    queryKey: [PRODUCT_QUERY_KEY, id],
    queryFn: async () => {
      const res = await request({ url: `/products/${id}`, method: 'GET' })
      return res
    },
    enabled: !!id
  })
}

export const useUpdateProduct = () => {
  return useCustomMutation<{ id: string; payload: Record<string, any> }, IBaseResponse<IProduct>>(
    ['products-update'],
    async ({ id, payload }) => {
      const res = await request({
        url: `/products/${id}`,
        method: 'PUT',
        data: payload
      })
      return res
    },
    {
      onSuccess: async () => {
        revalidatePath('')
      }
    }
  )
}

export const useUpdateProductImage = () => {
  return useCustomMutation<{ id: string; payload: { image: File } }, IBaseResponse<IProduct>>(
    ['products-update-image'],
    async ({ id, payload }) => {
      const formData = new FormData()
      formData.append('image', payload.image)

      const res = await request({
        url: `/products/${id}/update-image`,
        method: 'POST',
        data: formData
      })
      return res
    },
    {
      invalidateQueries: [PRODUCT_QUERY_KEY]
    }
  )
}

export const useDeleteProduct = () => {
  return useCustomMutation<string, IBaseResponse<void>>(
    ['products-delete'],
    async (id: string) => {
      const res = await request({
        url: `/products/${id}`,
        method: 'DELETE'
      })
      return res
    },
    {
      invalidateQueries: ['simple-products-list']
    }
  )
}
