/**
 * 認證功能冒煙測試
 * 
 * 此測試用於 Dev/QA 環境，快速驗證認證功能是否正常運作。
 * 測試重點：基本功能可用性，不關注性能。
 */

import { registerWithCredentials, loginWithCredentials, refreshToken } from '../../scenarios/apis/auth.js';
import { healthCheck } from '../../scenarios/apis/health.js';

export const options = {
  scenarios: {
    smoke_auth: {
      executor: 'shared-iterations',
      vus: 1,
      iterations: 1,
      maxDuration: '30s',
      tags: { test_type: 'smoke', api: 'auth' },
    },
  },
  thresholds: {
    checks: ['rate==1.0'], // 所有檢查必須通過
    http_req_duration: ['p(95)<2000'], // 95% 的請求應在 2 秒內完成
  },
};

export default function () {
  const baseUrl = __ENV.BASE_URL || 'http://localhost:8888';
  const timestamp = Date.now();
  const loginId = `smoke_test_${timestamp}@example.com`;
  const password = 'SmokeTest123!';

  // 1. 健康檢查
  healthCheck({ baseUrl });

  // 2. 註冊
  const registerResult = registerWithCredentials({
    baseUrl,
    loginId,
    password,
  });

  if (!registerResult.success) {
    console.error('Smoke test failed: Registration failed');
    return;
  }

  // 3. 登入
  const loginResult = loginWithCredentials({
    baseUrl,
    loginId,
    password,
  });

  if (!loginResult.success) {
    console.error('Smoke test failed: Login failed');
    return;
  }

  // 4. 刷新 Token
  if (loginResult.tokens) {
    const refreshResult = refreshToken({
      baseUrl,
      accessToken: loginResult.tokens.accessToken,
      refreshToken: loginResult.tokens.refreshToken,
    });

    if (!refreshResult.success) {
      console.error('Smoke test failed: Token refresh failed');
      return;
    }
  }

  console.log('Smoke test passed: All auth operations succeeded');
}

