import axios from "axios";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { BASE_URL, STORAGE_KEYS } from "../constants/config";
import { router } from "expo-router";

const api = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
});

// Request interceptor to add auth token
api.interceptors.request.use(async (config) => {
  const token = await AsyncStorage.getItem(STORAGE_KEYS.AUTH_TOKEN);

  // Debug log for request
  console.log("🚀 [API Request]");
  console.log("➡️ Full URL:", `${config.baseURL || ""}${config.url}`);
  console.log("➡️ Method:", config.method?.toUpperCase());
  console.log("➡️ Headers (before token):", config.headers);
  console.log("➡️ Body/Data:", config.data);

  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
    console.log("✅ Auth token attached");
  } else {
    console.log("⚠️ No auth token found");
  }

  return config;
});

// Response interceptor to handle errors
api.interceptors.response.use(
  (response) => {
    // Debug log for successful response
    console.log("✅ [API Response]");
    console.log("⬅️ Status:", response.status);
    console.log("⬅️ Data:", response.data);
    return response;
  },
  async (error) => {
    const status = error.response?.status;

    // Debug log for error
    console.log("❌ [API Error]");
    console.log("URL:", error.config?.url);
    console.log("Status:", status);
    console.log("Response data:", error.response?.data);

    // If token is expired or not present
    if (status === 401 || status === 403) {
      console.log("Token expired or not present");
      await AsyncStorage.removeItem(STORAGE_KEYS.AUTH_TOKEN);
      router.replace("/auth/login");
    }

    return Promise.reject(error);
  }
);

export default api;
