import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '../stores/auth';

export interface ApiResult<T> {
  success: boolean;
  data: T;
  error?: {
    code: string;
    message: string;
  };
  requestId?: string;
  timestamp?: number;
}

export interface PageResult<T> {
  records: T[];
  total: number;
  page: number;
  size: number;
}

const client = axios.create({
  baseURL: '/admin-api',
  timeout: 20000,
});

client.interceptors.request.use((config) => {
  const auth = useAuthStore();
  if (auth.token) {
    config.headers['satoken-admin'] = auth.token;
  }
  return config;
});

client.interceptors.response.use(
  (response) => {
    const body = response.data as ApiResult<unknown>;
    if (body && body.success === false) {
      ElMessage.error(body.error?.message || '请求失败');
      return Promise.reject(new Error(body.error?.message || '请求失败'));
    }
    return body?.data ?? response.data;
  },
  (error) => {
    if (error.response?.status === 401) {
      const auth = useAuthStore();
      auth.logoutLocal();
      window.location.replace('/auth/login');
    }
    const message =
      error.response?.data?.error?.message ||
      (error.response?.status >= 500
        ? '后端管理服务未启动或接口异常，请确认后端已按根目录 .env 的 BACKEND_PORT 启动'
        : error.message || '网络异常');
    ElMessage.error(message);
    return Promise.reject(error);
  },
);

export const http = {
  get<T = any>(url: string, config?: any): Promise<T> {
    return client.get(url, config) as unknown as Promise<T>;
  },
  post<T = any>(url: string, data?: any, config?: any): Promise<T> {
    return client.post(url, data, config) as unknown as Promise<T>;
  },
  patch<T = any>(url: string, data?: any, config?: any): Promise<T> {
    return client.patch(url, data, config) as unknown as Promise<T>;
  },
  put<T = any>(url: string, data?: any, config?: any): Promise<T> {
    return client.put(url, data, config) as unknown as Promise<T>;
  },
};
