import { getServerToken } from './auth';

type ResponseType<T = any> = {
  code: number;
  message: string;
  data: T;
};

export async function fetchServerRequest<T = any>(
  url: string,
  options?: {
    method?: 'GET' | 'POST';
    params?: Record<string, any>;
    data?: Record<string, any>;
    requireAuth?: boolean;
    // Next.js 缓存选项
    revalidate?: number | false; // 秒数，或 false 表示永不过期
    tags?: string[]; // 缓存标签，用于手动刷新
  }
): Promise<ResponseType<T>> {
  const { method = 'POST', params, data, requireAuth = false, revalidate, tags } = options || {};

  // 获取 token（如果需要）
  let token: string | null = null;
  if (requireAuth) {
    token = await getServerToken();
    if (!token) {
      throw new Error('Authentication required');
    }
  }

  // 构建请求配置
  const fetchOptions: RequestInit = {
    method,
    headers: {
      'Content-Type': 'application/json',
      ...(token && { Authorization: `Bearer ${token}` }),
    },
    // Next.js 缓存配置
    next: {
      ...(revalidate !== undefined && { revalidate }),
      ...(tags && { tags }),
    },
  };

  // 构建完整 URL（服务端必须用完整 URL）
  const baseURL = 'http://54.223.196.180';
  const fullURL = new URL(url, baseURL);

  // 处理查询参数
  if (params) {
    Object.entries(params).forEach(([key, value]) => {
      if (value !== '') {
        fullURL.searchParams.append(key, String(value));
      }
    });
  }

  // 处理 body 数据
  if (data) {
    fetchOptions.body = JSON.stringify(
      Object.fromEntries(Object.entries(data).filter(([, value]) => value !== ''))
    );
  }

  // 发起请求
  const response = await fetch(fullURL.toString(), fetchOptions);
  if (!response.ok) {
    return { code: 400, message: '请求失败', data: {} as T };
  }

  return await response.json();
}

export async function serverRequest<T = any>(
  url: string,
  options?: {
    method?: 'GET' | 'POST';
    params?: Record<string, any>;
    data?: Record<string, any>;
    revalidate?: number | false;
    tags?: string[];
  }
): Promise<ResponseType<T>> {
  return fetchServerRequest<T>(url, { ...options, requireAuth: false });
}
