import axios from "axios";
import { getAuthToken, useAuthStore } from "../../stores/authStore";

const BASE_URL = import.meta.env.VITE_API_BASE_URL ?? "/api";
const AUTH_ROUTES = new Set(["/login", "/register"]);
let isRedirectingToLogin = false;

export const apiClient = axios.create({
  baseURL: BASE_URL,
  timeout: 180_000,
  headers: {
    "Content-Type": "application/json",
  },
});

function redirectToLogin() {
  if (typeof window === "undefined" || isRedirectingToLogin) return;

  try {
    localStorage.removeItem("yaoai_token");
  } catch {
    // Ignore storage access errors in restricted browser contexts.
  }

  useAuthStore.getState().clearAuth();

  if (AUTH_ROUTES.has(window.location.pathname)) return;

  isRedirectingToLogin = true;
  const redirect = `${window.location.pathname}${window.location.search}${window.location.hash}`;
  window.location.replace(`/login?redirect=${encodeURIComponent(redirect)}`);
}

// Request interceptor: attach Bearer token from the persisted auth store
apiClient.interceptors.request.use((config) => {
  const token = getAuthToken() ?? localStorage.getItem("yaoai_token");
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Response interceptor: unwrap ApiResponse.data, handle errors
apiClient.interceptors.response.use(
  (response) => {
    const body = response.data;
    if (body?.success === false) {
      return Promise.reject(
        new ApiError(body.error?.code ?? "UNKNOWN", body.error?.message ?? "Unknown error")
      );
    }
    return response;
  },
  (error) => {
    if (error.response?.data?.error) {
      const { code, message } = error.response.data.error;
      if (code === "UNAUTHORIZED") {
        redirectToLogin();
      }
      return Promise.reject(new ApiError(code, message));
    }
    if (error.response?.status >= 500) {
      const status = error.response.status;
      return Promise.reject(
        new ApiError(
          "SERVER_UNAVAILABLE",
          `后端接口异常（HTTP ${status}），请查看后端日志；同时确认 yaoai-comic-studio 已按根目录 .env 的 BACKEND_PORT 启动`
        )
      );
    }
    if (error.code === "ERR_NETWORK" || error.code === "ECONNABORTED") {
      return Promise.reject(
        new ApiError(
          "NETWORK_ERROR",
          "无法连接后端服务，请确认本地后端与数据库已启动"
        )
      );
    }
    return Promise.reject(error);
  }
);

export class ApiError extends Error {
  constructor(
    public readonly code: string,
    message: string
  ) {
    super(message);
    this.name = "ApiError";
  }
}
