import { adminApi } from './client'
import { unwrapList } from './helpers'
import { normalizeSetting } from './normalizers'
import type { AdminSettingRecord, ApiListResponse } from './types'

export async function fetchSettings(): Promise<AdminSettingRecord[]> {
  const response =
    await adminApi.get<ApiListResponse<Record<string, unknown>>>('/settings')
  return unwrapList(response).map(normalizeSetting)
}

export async function fetchSettingsByGroup(
  group: string
): Promise<AdminSettingRecord[]> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    `/settings/group/${group}`
  )
  return unwrapList(response).map(normalizeSetting)
}

export async function updateSettings(
  settings: Record<string, string | null>
) {
  await adminApi.put('/settings', { settings })
}

export async function clearSettingsCache() {
  await adminApi.post('/settings/clear-cache')
}
