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

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

  return executeFetch<StatsResponse<Attribute>>({
    accessToken,
    signal,
    url: statsUrl,
    method: RequestMethods.get,
    params: { ...params },
    ...other,
  })
}
