import { signRequest, SignerOptions } from './signer';
import { DEFAULT_REGION, DEFAULT_BASE_URL } from '../consts';
import { logger } from './logger';

export interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
  request_id: string;
}

export interface RequestOptions {
  pathname: string;
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
  body?: any;
  region?: string;
  params?: Record<string, any>;
  headers?: Record<string, string>;
  baseURL?: string;
}

/**
 * 封装火山引擎API请求
 * @param options 请求参数
 * @param accessKeyId 用户AK
 * @param secretKey 用户SK
 * @returns Promise<Response>
 */
export async function request<T>(
  options: RequestOptions,
  accessKeyId?: string,
  secretKey?: string
): Promise<ApiResponse<T>> {
  logger.debug(`[API Request] Starting request ${options.pathname} ${options.method}`);
  const { pathname, method, body, params, headers } = options;
  
  const region = options.region || process.env.REAI_VOLC_REGION || DEFAULT_REGION;
  const baseURL = options.baseURL || process.env.REAI_VOLC_BASE_URL || DEFAULT_BASE_URL;
  
  // 生成签名
  const signerOptions: SignerOptions = {
    pathname,
    method,
    body: body ? JSON.stringify(body) : undefined,
    region: region,
    params
  };
  
  const signedHeaders = signRequest(signerOptions, accessKeyId, secretKey);
  logger.debug(`[API Request] Signed headers generated ${JSON.stringify(signedHeaders)}`);
  
  // 合并请求头
  const requestHeaders = {
    ...headers,
    ...signedHeaders
  };
  
  // 构建URL
  let url = baseURL ? `${baseURL}${pathname}` : pathname;
  if (params) {
    const query = new URLSearchParams(params);
    url += `?${query.toString()}`;
  }
  
  // 配置fetch请求
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 10000);
  
  try {
    logger.debug(`[API Request] Sending request to ${url}`);
    const response = await fetch(url, {
      method,
      headers: requestHeaders,
      body: method !== 'GET' ? JSON.stringify(body) : undefined,
      signal: controller.signal
    });
    
    clearTimeout(timeoutId);
    
    if (!response.ok) {
      logger.error(`[API Request] Request failed ${response.status} ${response.statusText}`);
      throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
    }
    logger.debug(`[API Request] Request succeeded ${response.status}`);
    
    const result = await response.json();
    return result as ApiResponse<T>;
  } catch (error) {
    clearTimeout(timeoutId);
    if (error instanceof Error) {
      logger.error(`[API Request] Request error ${error.message}`);
      throw new Error(`API请求失败: ${error.message}`);
    }
    throw error;
  }
}