import { useQuery } from '@tanstack/react-query'
import { api } from '../api'
import { Campaign, CampaignRule, Campaigns } from '@/types/services/campaign'

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

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

  return useQuery<Campaigns>({
    queryKey: ['campaigns', { 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(`/marketing/campaigns?${queryParams.toString()}`)
      return res.data.data
    }
  })
}

export function useCampaignById(id: string) {
  return useQuery<Campaign>({
    queryKey: ['campaigns', id],
    queryFn: async () => {
      const res = await api.get(`/marketing/campaigns/${id}`)
      return res.data.data
    }
  })
}

export function useCampaignRulesByCampaignId(id: string) {
  return useQuery<CampaignRule[]>({
    queryKey: ['campaign-rules/campaign', id],
    queryFn: async () => {
      const res = await api.get(`/marketing/campaign-rules/campaign/${id}`)
      return res.data.data
    }
  })
}
