import axios from 'axios';
import { buildLoginRedirectUrl, getCurrentRelativePath } from './auth-redirect';

// 导出 API_URL 供其他模块使用
export const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1';

export const api = axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  // 正确序列化数组参数 (groupIds=[id1,id2] -> groupIds=id1&groupIds=id2)
  paramsSerializer: (params) => {
    const searchParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      if (Array.isArray(value)) {
        // 数组：重复参数名 (groupIds=id1&groupIds=id2)
        value.forEach(item => searchParams.append(key, String(item)));
      } else if (value !== undefined && value !== null) {
        // 普通值
        searchParams.append(key, String(value));
      }
    });
    return searchParams.toString();
  },
});

// 获取 token 的辅助函数
const getToken = () => {
  // 优先从 localStorage 获取
  const token = localStorage.getItem('token');
  if (token) return token;

  // 如果 localStorage 中没有，尝试从 Zustand 持久化存储中获取
  try {
    const authStorage = localStorage.getItem('auth-storage');
    if (authStorage) {
      const { state } = JSON.parse(authStorage);
      return state?.token || null;
    }
  } catch (error) {
    console.error('Failed to parse auth storage:', error);
  }
  return null;
};

// 清除所有认证信息的辅助函数
const clearAuth = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('auth-storage');
};

// 请求拦截器 - 添加 Token
api.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误 + 自动捕获 refreshToken
const REFRESH_TOKEN_KEY = 'refresh_token';

api.interceptors.response.use(
  (response) => {
    // 与 api-client.ts 保持一致：自动从 /auth/login / /auth/dev-email-login / /auth/refresh
    // 响应里抓取 refreshToken 存到 localStorage（规则 §2.2）
    const url = response.config.url || '';
    const isAuthEndpoint =
      url.includes('/auth/login') ||
      url.includes('/auth/dev-email-login') ||
      url.includes('/auth/refresh');
    if (isAuthEndpoint && typeof window !== 'undefined') {
      const data = response.data?.data;
      if (data?.refreshToken) {
        localStorage.setItem(REFRESH_TOKEN_KEY, data.refreshToken);
      }
    }
    return response.data;
  },
  (error) => {
    if (error.response?.status === 401) {
      // 清除所有认证信息
      clearAuth();
      if (typeof window !== 'undefined') {
        localStorage.removeItem(REFRESH_TOKEN_KEY);
      }
      // 只有不是登录页面时才跳转
      if (typeof window !== 'undefined' && window.location.pathname !== '/login') {
        window.location.href = buildLoginRedirectUrl(getCurrentRelativePath());
      }
    }
    return Promise.reject(error);
  }
);

// 认证 API
export const authApi = {
  login: (data: { username: string; password: string }) =>
    api.post('/auth/login', data),
  devEmailLogin: (data: { email: string }) =>
    api.post('/auth/dev-email-login', data),
  register: (data: { username: string; email: string; password: string; displayName: string }) =>
    api.post('/auth/register', data),
};

// 用户 API
export const userApi = {
  getUsers: (params?: any) => api.get('/users', { params }),
  getUserById: (id: string) => api.get(`/users/${id}`),
  createUser: (data: any) => api.post('/users', data),
  updateUser: (id: string, data: any) => api.patch(`/users/${id}`, data),
  deleteUser: (id: string) => api.delete(`/users/${id}`),
};

// 部门 API
export const departmentApi = {
  getDepartments: () => api.get('/departments'),
  getDepartmentTree: () => api.get('/departments/tree'),
  getDepartmentById: (id: string) => api.get(`/departments/${id}`),
  createDepartment: (data: any) => api.post('/departments', data),
  updateDepartment: (id: string, data: any) => api.patch(`/departments/${id}`, data),
  deleteDepartment: (id: string) => api.delete(`/departments/${id}`),
};

// 岗位 API
export const positionApi = {
  getPositions: () => api.get('/positions'),
  getPositionById: (id: string) => api.get(`/positions/${id}`),
  createPosition: (data: any) => api.post('/positions', data),
  updatePosition: (id: string, data: any) => api.patch(`/positions/${id}`, data),
  deletePosition: (id: string) => api.delete(`/positions/${id}`),
};

// 报销 API
export const expenseApi = {
  getMyExpenses: (params?: any) => api.get('/expenses/my', { params }),
  getPendingExpenses: () => api.get('/expenses/pending'),
  getExpenseById: (id: string) => api.get(`/expenses/${id}`),
  createExpense: (data: any) => api.post('/expenses', data),
  updateExpense: (id: string, data: any) => api.patch(`/expenses/${id}`, data),
  deleteExpense: (id: string) => api.delete(`/expenses/${id}`),
  submitExpense: (id: string) => api.post(`/expenses/${id}/submit`),
  approveExpense: (id: string, data: any) => api.post(`/expenses/${id}/approve`, data),
};

// 采购 API
export const purchaseApi = {
  getMyPurchases: (params?: any) => api.get('/purchases/my', { params }),
  getPendingPurchases: () => api.get('/purchases/pending'),
  getPurchaseById: (id: string) => api.get(`/purchases/${id}`),
  createPurchase: (data: any) => api.post('/purchases', data),
  updatePurchase: (id: string, data: any) => api.patch(`/purchases/${id}`, data),
  deletePurchase: (id: string) => api.delete(`/purchases/${id}`),
  submitPurchase: (id: string) => api.post(`/purchases/${id}/submit`),
  approvePurchase: (id: string, data: any) => api.post(`/purchases/${id}/approve`, data),
  markAsReceived: (id: string, data: any) => api.post(`/purchases/${id}/receive`, data),
};

// 合同 API
export const contractApi = {
  getMyContracts: (params?: any) => api.get('/contracts/my', { params }),
  getPendingContracts: () => api.get('/contracts/pending'),
  getContractById: (id: string) => api.get(`/contracts/${id}`),
  createContract: (data: any) => api.post('/contracts', data),
  updateContract: (id: string, data: any) => api.patch(`/contracts/${id}`, data),
  deleteContract: (id: string) => api.delete(`/contracts/${id}`),
  submitContract: (id: string) => api.post(`/contracts/${id}/submit`),
  approveContract: (id: string, data: any) => api.post(`/contracts/${id}/approve`, data),
  applySeal: (id: string) => api.post(`/contracts/${id}/apply-seal`),
};

// 通知 API
export const notificationApi = {
  getNotifications: (params?: any) => api.get('/notifications', { params }),
  getUnreadCount: () => api.get('/notifications/unread-count'),
  markAsRead: (id: string) => api.patch(`/notifications/${id}/read`),
  markAllAsRead: () => api.post('/notifications/mark-all-read'),
  getPreferences: () => api.get('/notifications/preferences'),
  updatePreferences: (data: any) => api.patch('/notifications/preferences', data),
};

// 审计日志 API
export const auditApi = {
  getAuditLogs: (params?: any) => api.get('/audit', { params }),
  getResourceHistory: (type: string, id: string) => api.get(`/audit/resource/${type}/${id}`),
  generateReport: (params: any) => api.get('/audit/report', { params }),
  verifyIntegrity: (id: string) => api.get(`/audit/verify/${id}`),
};
