import axios from "axios";
import { getBrowserToken } from "@/lib/auth/token";

export const apiClient = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_BASE_URL,
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
  timeout: 15000,
});

apiClient.interceptors.request.use((config) => {
  const token = getBrowserToken();

  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  if (typeof window !== "undefined") {
    const locale = window.localStorage.getItem("web_locale");
    const countryId = window.localStorage.getItem("web_country_id");

    if (locale) {
      config.headers["X-App-Locale"] = locale;
    }

    if (countryId) {
      config.headers["X-Country-Id"] = countryId;
    }
  }

  return config;
});

export type ApiResponse<T> = {
  success: boolean;
  message: string;
  data: T;
  meta?: {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
  };
  errors?: Record<string, string[]>;
};

export const getApiErrorMessage = (error: unknown): string => {
  if (axios.isAxiosError(error)) {
    return (
      (error.response?.data as { message?: string } | undefined)?.message ||
      "حدث خطأ في الاتصال بالخادم"
    );
  }

  if (error instanceof Error) {
    return error.message;
  }

  return "حدث خطأ غير متوقع";
};
