/**
 * 健康檢查 API 場景模組
 * 
 * 此模組提供系統健康檢查場景，用於監控系統狀態。
 * 
 * 使用方式：
 * import { healthCheck } from './scenarios/apis/health.js';
 */

import http from 'k6/http';
import { check } from 'k6';
import { Rate, Trend } from 'k6/metrics';

// 可選的自定義指標
const healthCheckSuccessRate = new Rate('health_check_success');
const healthCheckDuration = new Trend('health_check_duration');

/**
 * 系統健康檢查
 * @param {Object} options - 配置選項
 * @param {string} options.baseUrl - API 基礎 URL
 * @param {Object} options.customMetrics - 自定義指標對象（可選）
 * @returns {Object} 健康檢查結果
 */
export function healthCheck(options = {}) {
  const {
    baseUrl = __ENV.BASE_URL || 'http://localhost:8888',
    customMetrics = null,
  } = options;

  const url = `${baseUrl}/api/v1/health`;

  const params = {
    headers: {
      'Content-Type': 'application/json',
    },
    tags: {
      name: 'health_check',
      api: 'health',
      method: 'health_check',
    },
  };

  const startTime = Date.now();
  const res = http.get(url, params);
  const duration = Date.now() - startTime;

  const success = check(res, {
    'health check status is 200': (r) => r.status === 200,
    'health check response time < 500ms': (r) => r.timings.duration < 500,
  }, { name: 'health_check_checks' });

  if (customMetrics) {
    customMetrics.healthCheckSuccessRate?.add(success);
    customMetrics.healthCheckDuration?.add(duration);
  } else {
    healthCheckSuccessRate.add(success);
    healthCheckDuration.add(duration);
  }

  return {
    success,
    status: res.status,
    responseTime: res.timings.duration,
  };
}

