import axios from 'axios';
import CloudSyncStorage from '../services/cloudSyncStorage';

const showNotification = (message: string, type: 'error' | 'success' = 'error') => {
  if ((window as any).showToast) {
    (window as any).showToast(message, type);
  } else {
    window.alert(message);
  }
};

let lastOpenCloudSyncSettingsAt = 0;
const requestCloudSyncReLogin = (): void => {
  const now = Date.now();
  if (now - lastOpenCloudSyncSettingsAt < 1500) return;
  lastOpenCloudSyncSettingsAt = now;
  window.dispatchEvent(new CustomEvent('openCloudSyncSettings'));
};

/**
 * 云同步专用 HTTP Client。
 *
 * 注意：本项目现有 `client.ts` 的 baseURL 固定为 `window.__API_BASE_URL__`（通常已包含 `/api`），
 * 但云同步服务端端点位于根路径（`/auth/*`、`/tasks/*` 等）。
 * 因此云同步需要独立的 baseURL（用户配置的服务端地址）。
 */
const cloudClient = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

cloudClient.interceptors.request.use((config) => {
  const { serverUrl } = CloudSyncStorage.loadSettings();
  if (serverUrl) {
    config.baseURL = serverUrl;
  }

  const session = CloudSyncStorage.loadSession();
  if (session?.accessToken) {
    config.headers = config.headers ?? {};
    (config.headers as any).Authorization = `Bearer ${session.accessToken}`;
  }

  return config;
});

cloudClient.interceptors.response.use(
  (response) => response,
  (error) => {
    let errorMessage = '网络错误，请稍后再试';

    const status = error?.response?.status as number | undefined;
    if (status === 401 || status === 403) {
      CloudSyncStorage.clearSession();
      requestCloudSyncReLogin();
      errorMessage = status === 401 ? '云同步会话已过期，请重新登录' : '云同步权限不足，请重新登录或联系管理员';
      showNotification(errorMessage, 'error');
      return Promise.reject(error);
    }

    if (error?.response?.data) {
      const data = error.response.data;
      if (typeof data === 'string' && data.trim()) {
        errorMessage = data;
      } else if (data && typeof data === 'object') {
        const message = (data.message ?? data.Message) as unknown;
        const errors = (data.errors ?? data.Errors) as unknown;

        if (Array.isArray(errors) && errors.length > 0) {
          errorMessage = errors.join('\n');
        } else if (typeof message === 'string' && message.trim()) {
          errorMessage = message;
        }
      }
    } else if (typeof error?.message === 'string' && error.message.trim()) {
      errorMessage = error.message;
    }

    showNotification(errorMessage, 'error');
    return Promise.reject(error);
  }
);

export default cloudClient;
