import { get, patch, del } from './client.js';

/**
 * Fetch results with optional filters
 * @param {Object} params - Query parameters
 * @param {number} [params.order_id] - Filter by order ID
 * @param {number} [params.patient_id] - Filter by patient ID
 * @param {number} [params.page] - Page number
 * @param {number} [params.per_page] - Items per page
 * @returns {Promise<Object>} Results list response
 */
export async function fetchResults(params = {}) {
  const query = new URLSearchParams();
  
  if (params.order_id) query.append('order_id', params.order_id);
  if (params.patient_id) query.append('patient_id', params.patient_id);
  if (params.page) query.append('page', params.page);
  if (params.per_page) query.append('per_page', params.per_page);
  
  const queryString = query.toString();
  return get(queryString ? `/api/results?${queryString}` : '/api/results');
}

/**
 * Fetch a single result by ID
 * @param {number} id - Result ID
 * @returns {Promise<Object>} Result details
 */
export async function fetchResultById(id) {
  return get(`/api/results/${id}`);
}

/**
 * Update a result value with auto-validation
 * @param {number} id - Result ID
 * @param {Object} data - Result data
 * @param {string} data.Result - The result value
 * @param {number} [data.RefNumID] - Reference range ID
 * @param {string} [data.SampleType] - Sample type
 * @param {number} [data.WorkstationID] - Workstation ID
 * @param {number} [data.EquipmentID] - Equipment ID
 * @returns {Promise<Object>} Updated result with flag
 */
export async function updateResult(id, data) {
  return patch(`/api/results/${id}`, data);
}

/**
 * Delete a result (soft delete)
 * @param {number} id - Result ID
 * @returns {Promise<Object>} Success response
 */
export async function deleteResult(id) {
  return del(`/api/results/${id}`);
}

/**
 * Fetch results by order ID
 * @param {number} orderId - Order ID
 * @returns {Promise<Object>} Results list for order
 */
export async function fetchResultsByOrder(orderId) {
  return fetchResults({ order_id: orderId });
}

/**
 * Fetch cumulative results by patient ID
 * @param {number} patientId - Patient ID
 * @param {number} [page] - Page number
 * @param {number} [perPage] - Items per page
 * @returns {Promise<Object>} Patient results history
 */
export async function fetchResultsByPatient(patientId, page = 1, perPage = 20) {
  return fetchResults({ patient_id: patientId, page, per_page: perPage });
}
