'use client'

import { useQueryClient } from '@tanstack/react-query'

import { IBaseResponse } from '@/@core/types/api'
import { ITable } 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'

const invalidateTableQueries = async (queryClient: ReturnType<typeof useQueryClient>, tableId?: string) => {
  const tasks = [
    queryClient.invalidateQueries({ queryKey: [TABLES_LIST_QUERY_KEY] }),
    tableId ? queryClient.invalidateQueries({ queryKey: [TABLE_STATUS_QUERY_KEY, tableId] }) : Promise.resolve()
  ]

  await Promise.all(tasks)
}

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

  return useCustomMutation<string, IBaseResponse<ITable>>(
    ['tables-toggle-active'],
    tableId =>
      request({
        url: `/tables/${tableId}/toggle-active`,
        method: 'PATCH'
      }),
    {
      onSuccess: async (_, tableId) => {
        await invalidateTableQueries(queryClient, tableId)
      }
    }
  )
}

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

  return useCustomMutation<string, IBaseResponse<any>>(
    ['tables-release'],
    tableId =>
      request({
        url: `/tables/${tableId}/release`,
        method: 'PATCH'
      }),
    {
      onSuccess: async (_, tableId) => {
        await invalidateTableQueries(queryClient, tableId)
      }
    }
  )
}

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

  return useCustomMutation<string, IBaseResponse<ITable>>(
    ['tables-activate'],
    tableId =>
      request({
        url: `/tables/${tableId}/activate`,
        method: 'PATCH'
      }),
    {
      onSuccess: async (_, tableId) => {
        await invalidateTableQueries(queryClient, tableId)
      }
    }
  )
}

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

  return useCustomMutation<string, IBaseResponse<ITable>>(
    ['tables-deactivate'],
    tableId =>
      request({
        url: `/tables/${tableId}/deactivate`,
        method: 'PATCH'
      }),
    {
      onSuccess: async (_, tableId) => {
        await invalidateTableQueries(queryClient, tableId)
      }
    }
  )
}
