import { APP_COMPANY } from "../config/company";

// 后端地址跟随公司开关（src/config/company.ts 的 ACTIVE_COMPANY）一起切换
export const API_BASE_URL = APP_COMPANY.apiBaseUrl;
export const WEB_BASE_URL = APP_COMPANY.webBaseUrl;

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

interface RequestOptions {
  data?: Record<string, unknown>;
  header?: Record<string, string>;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
}

export function request<T>(url: string, options: RequestOptions = {}) {
  return new Promise<T>((resolve, reject) => {
    uni.request({
      url: `${API_BASE_URL}${url}`,
      method: options.method ?? 'GET',
      data: options.data,
      header: {
        'content-type': 'application/json',
        ...options.header,
      },
      success: (response) => {
        const result = response.data as ApiResponse<T>;
        if (result?.code === 0) {
          resolve(result.data);
          return;
        }
        if (response.statusCode === 401 || result?.code === 401) {
          uni.$emit('auth-expired');
          reject(new Error('登录已过期，请重新登录'));
          return;
        }
        reject(new Error(result?.msg || '请求失败，请稍后重试'));
      },
      fail: () => reject(new Error('网络连接失败，请检查网络后重试')),
    });
  });
}
