'use client'

import { useCustomQuery } from '@/hooks/api'
import { request } from '@/utils'
import { CustomUseQueryOptions, IBaseResponse, IPaginatedData, TPaginationModel, TSearch } from '@/@core/types/api'
import { IPaymentMethodDetails } from '@/types/data/payment-method'

export const PAYMENT_METHODS_LIST_QUERY_KEY = 'payment-methods-list'

export type PaymentMethodsListQuery = Partial<TPaginationModel & TSearch> & {
  type?: 'online' | 'offline'
  is_active?: number | boolean
  requires_online_payment?: number | boolean
  sort_by?: 'sort_order' | 'code' | 'name_en' | 'created_at'
  sort_as?: 'asc' | 'desc'
  with_deleted?: number | boolean
}

export const useGetPaymentMethodsList = (
  query?: PaymentMethodsListQuery,
  options?: CustomUseQueryOptions<IBaseResponse<IPaginatedData<IPaymentMethodDetails[]>>>
) => {
  const queryKey = [PAYMENT_METHODS_LIST_QUERY_KEY, query]

  return useCustomQuery<IBaseResponse<IPaginatedData<IPaymentMethodDetails[]>>>(queryKey, () => {
    const params: Record<string, string> = {}

    const perPage = query?.per_page ?? 12
    params.per_page = String(perPage)

    if (query?.page !== undefined) {
      params.page = String(query.page)
    }

    if (query) {
      Object.entries(query).forEach(([key, value]) => {
        if (value === undefined || value === null || value === '' || key === 'per_page' || key === 'page') {
          return
        }

        if (typeof value === 'boolean') {
          params[key] = value ? '1' : '0'
        } else {
          params[key] = String(value)
        }
      })
    }

    return request<IBaseResponse<IPaginatedData<IPaymentMethodDetails[]>>>({
      url: '/payment-methods',
      params
    })
  }, options)
}
