import axios from "axios";

const BASE_URL = import.meta.env.VITE_API_BASE_URL ?? "/api";

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

// Request interceptor: attach Bearer token from localStorage
apiClient.interceptors.request.use((config) => {
  const token = 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;
      return Promise.reject(new ApiError(code, message));
    }
    return Promise.reject(error);
  }
);

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