import axios from 'axios';
import { buildRoute } from '@/utils/route';

const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'https://yisheng.cpolar.cn';

const api = axios.create({
  baseURL: API_BASE,
  timeout: 30000,
});

// 请求拦截：自动附加 JWT Token
api.interceptors.request.use((config) => {
  if (typeof window !== 'undefined') {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
  }
  return config;
});

// 响应拦截：401 跳转登录
api.interceptors.response.use(
  (res) => res,
  (err) => {
    if (err.response?.status === 401 && typeof window !== 'undefined') {
      localStorage.removeItem('token');
      const ROUTE_PRE = process.env.NEXT_PUBLIC_ROUTE_PRE || '';
      const loginPath = ROUTE_PRE ? `/${ROUTE_PRE}/login` : '/login';
      window.location.href = loginPath;
    }
    return Promise.reject(err);
  }
);

export default api;

// ============ Auth ============
export const login = (username: string, password: string) =>
  api.post('/api/admin/auth/login', { username, password });
export const changePassword = (oldPassword: string, newPassword: string) =>
  api.put('/api/admin/auth/password', { old_password: oldPassword, new_password: newPassword });

// ============ Dashboard ============
export const getDashboardStats = () => api.get('/api/admin/dashboard/stats');
export const getDashboardTrend = () => api.get('/api/admin/dashboard/trend');

// ============ Clients ============
export const getClients = (params?: Record<string, unknown>) =>
  api.get('/api/admin/clients', { params });
export const createClient = (data: Record<string, unknown>) =>
  api.post('/api/admin/clients', data);
export const updateClient = (id: number, data: Record<string, unknown>) =>
  api.put(`/api/admin/clients/update/${id}`, data);
export const toggleClient = (id: number) =>
  api.patch(`/api/admin/clients/toggle/${id}`);
export const generateApiKey = (clientId: number) =>
  api.post(`/api/admin/clients/api-keys/create/${clientId}`);
export const getClientApiKeys = (clientId: number) =>
  api.get(`/api/admin/clients/api-keys/${clientId}`);
export const deleteApiKey = (keyId: number) =>
  api.delete(`/api/admin/api-keys/delete/${keyId}`);

// ============ Permissions ============
export const getPermission = (apiKeyId: number) =>
  api.get(`/api/admin/permissions/${apiKeyId}`);
export const updatePermission = (apiKeyId: number, data: Record<string, unknown>) =>
  api.put(`/api/admin/permissions/${apiKeyId}`, data);

// ============ Logs ============
export const getLogs = (params?: Record<string, unknown>) =>
  api.get('/api/admin/logs', { params });
export const exportLogs = (params?: Record<string, unknown>) =>
  api.get('/api/admin/logs/export', { params, responseType: 'blob' });
