import { get } from './client.js';

/**
 * ValueSets API endpoints
 * System ValueSets are read-only lookup values used throughout the application
 */

/**
 * Fetch list of value set definitions
 * @param {Object} params - Query parameters
 * @param {string} [params.key] - Filter by value set key
 * @returns {Promise<{status: string, data: Array}>}
 */
export async function fetchValueSets(params = {}) {
  const queryParams = new URLSearchParams();
  
  if (params.key) {
    queryParams.append('key', params.key);
  }
  
  const query = queryParams.toString();
  const endpoint = query ? `/api/valueset?${query}` : '/api/valueset';
  
  return get(endpoint);
}

/**
 * Fetch a single value set by its key (includes items)
 * @param {string} key - Value set key (e.g., 'GENDER', 'MARITAL_STATUS')
 * @returns {Promise<{status: string, data: Object}>}
 */
export async function fetchValueSetByKey(key) {
  return get(`/api/valueset/${encodeURIComponent(key)}`);
}

/**
 * Fetch value set items
 * @param {Object} params - Query parameters
 * @param {string} [params.key] - Filter by value set key
 * @returns {Promise<{status: string, data: Array}>}
 */
export async function fetchValueSetItems(params = {}) {
  const queryParams = new URLSearchParams();
  
  if (params.key) {
    queryParams.append('key', params.key);
  }
  
  const query = queryParams.toString();
  const endpoint = query ? `/api/valueset/items?${query}` : '/api/valueset/items';
  
  return get(endpoint);
}

/**
 * Refresh value sets cache on the server
 * @param {Object} params - Request parameters
 * @param {string} [params.key] - Specific value set key to refresh (optional)
 * @returns {Promise<{status: string, message: string}>}
 */
export async function refreshValueSets(params = {}) {
  const { post } = await import('./client.js');
  return post('/api/valueset', params);
}

/**
 * Fetch a single value set item by ID
 * @param {number} itemId - Item ID
 * @returns {Promise<{status: string, data: Object}>}
 */
export async function fetchValueSetItemById(itemId) {
  return get(`/api/valueset/items/${itemId}`);
}
