import { useQuery } from '@tanstack/react-query'
import { Outlet, Outlets } from '../../types/services/outlet'
import { api } from '../api'

interface OutletsQueryParams {
  page?: number
  limit?: number
  search?: string
}

export function useOutlets(params: OutletsQueryParams = {}) {
  const { page = 1, limit = 10, search = '', ...filters } = params

  return useQuery<Outlets>({
    queryKey: ['outlets', { page, limit, search, ...filters }],
    queryFn: async () => {
      const queryParams = new URLSearchParams()

      queryParams.append('page', page.toString())
      queryParams.append('limit', limit.toString())

      if (search) {
        queryParams.append('search', search)
      }

      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          queryParams.append(key, value.toString())
        }
      })

      const res = await api.get(`/outlets/list?${queryParams.toString()}`)
      return res.data.data
    }
  })
}

export function useOutletById() {
  const user = (() => {
    try {
      return JSON.parse(localStorage.getItem('user') || '{}')
    } catch {
      return {}
    }
  })()

  const outletId = user?.outlet_id // atau sesuai struktur data user

  return useQuery<Outlet>({
    queryKey: ['outlet', outletId],
    queryFn: async () => {
      if (!outletId) throw new Error('Outlet ID not found in localStorage')
      const res = await api.get(`/outlets/detail/${outletId}`)
      return res.data.data
    },
    enabled: !!outletId // query hanya jalan kalau ada outletId
  })
}
