import {
  RequestMethods,
  executeFetch,
  DEFAULT_CARTO_API_URL,
  DEFAULT_CARTO_API_VERSION,
} from '@carto/ps-services'
import type { GetQueryStats } from './types'
import type { StatsResponse } from './types'

export async function getQueryStats<Attribute extends string | number>({
  baseUrl = DEFAULT_CARTO_API_URL,
  connection,
  accessToken,
  query,
  attribute,
  fetcherOptions: { signal, ...other } = {},
  queryParameters,
  params,
  apiVersion = DEFAULT_CARTO_API_VERSION,
}: GetQueryStats) {
  const statsUrl = `${baseUrl}/${apiVersion}/stats/${connection}/${attribute}`

  return executeFetch<StatsResponse<Attribute>>({
    accessToken,
    signal,
    url: statsUrl,
    method: RequestMethods.get,
    params: {
      q: query,
      ...params,
      ...(queryParameters !== undefined ? { queryParameters } : {}),
    },
    ...other,
  })
}
