'use client'

import { useQueryClient } from '@tanstack/react-query'
import { IBaseResponse } from '@/@core/types/api'
import { ITable, IUpdateTable } from '@/types/data/table'
import { request } from '@/utils'
import { TABLES_LIST_QUERY_KEY } from './useGetTablesList'
import { TABLE_STATUS_QUERY_KEY } from './useGetTableStatus'
import { useCustomMutation } from '@/hooks/api'

export interface UpdateTableVariables {
  tableId: string
  payload: IUpdateTable
}

export const useUpdateTable = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateTableVariables, IBaseResponse<ITable>>(
    ['tables-update'],
    ({ tableId, payload }) =>
      request<IBaseResponse<ITable>, IUpdateTable>({
        url: `/tables/${tableId}`,
        method: 'PUT',
        data: payload
      }),
    {
      onSuccess: async (_, { tableId }) => {
        await Promise.all([
          queryClient.invalidateQueries({ queryKey: [TABLES_LIST_QUERY_KEY] }),
          queryClient.invalidateQueries({ queryKey: [TABLE_STATUS_QUERY_KEY, tableId] })
        ])
      }
    }
  )
}
