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) {
      const message = body.error?.message || '请求失败';
      if (!message.includes('用户名或密码错误')) {
        ElMessage.error(message);
      }
      return Promise.reject(new Error(message));
    }
    return body?.data ?? response.data;
  },
  (error) => {
    const status = error.response?.status;
    let message =
      error.response?.data?.error?.message ||
      error.response?.data?.message ||
      (status === 401
        ? '登录已失效，请重新登录'
        : status === 403
        ? '没有权限访问'
        : status === 404
        ? '接口不存在（404），请检查后端是否按 V21~V39 升级并启动'
        : status >= 500
        ? `后端管理服务异常 (HTTP ${status})，请按根目录 .env 的 BACKEND_PORT 检查`
        : error.message || '网络异常');

    if (status === 401) {
      const auth = useAuthStore();
      auth.logoutLocal();
      if (!window.location.pathname.startsWith('/auth/login')) {
        const next = encodeURIComponent(window.location.pathname + window.location.search);
        window.location.replace(`/auth/login?next=${next}`);
      }
    }
    ElMessage.error(message);
    return Promise.reject(new Error(message));
  },
);

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>;
  },
  delete<T = any>(url: string, config?: any): Promise<T> {
    return client.delete(url, config) as unknown as Promise<T>;
  },
};
