// src/auth.js
import { jwtDecode } from "jwt-decode";
import axios from "axios";

const API_BASE_URL = `${import.meta.env.VITE_APP_API_BASE_URL}`
console.log("API_BASE_URL:", API_BASE_URL);
/**
 * Save auth data to localStorage
 */
const saveAuthData = (access, refresh, user) => {
  localStorage.setItem("accessToken", access);
  localStorage.setItem("refreshToken", refresh);
  localStorage.setItem("user", JSON.stringify(user));
};

/**
 * Refresh access token
 */
export const refreshAccessToken = async () => {
  const refresh = localStorage.getItem("refreshToken");
  if (!refresh) return false;

  try {
    const { data } = await axios.post(`${API_BASE_URL}/token/refresh/`, {
      refresh,
    });
    localStorage.setItem("accessToken", data.access);
    return true;
  } catch (error) {
    console.error("Token refresh failed:", error.response?.data || error.message);
    logout();
    return false;
  }
};

/**
 * Login and fetch user data
 */
export const login = async (email, password) => {
  try {
    // 1. Authenticate
    const tokenResponse = await axios.post(`${API_BASE_URL}/login/`, {
      email,
      password,
    });

    const { access, refresh } = tokenResponse.data;
    if (!access || !refresh) {
      throw new Error("Invalid login response: tokens missing");
    }

    // 2. Fetch user data with the new token
    const userResponse = await axios.get(`${API_BASE_URL}/user/me/`, {
      headers: { Authorization: `Bearer ${access}` },
    });

    const userData = userResponse.data;
    console.log(userData)

    // 3. Save everything
    saveAuthData(access, refresh, userData);

    return userData;
  } catch (error) {
    console.error("Login failed:", error.response?.data || error.message);
    return null;
  }
};

/**
 * Check if user is authenticated and verify via /user/me/
 */
export const isAuthenticated = async () => {
  try {
    let token = localStorage.getItem("accessToken");
    if (!token) return false;

    // Decode and check expiry
    const decoded = jwtDecode(token);
    if (decoded.exp * 1000 < Date.now()) {
      console.warn("Access token expired, refreshing...");
      const refreshed = await refreshAccessToken();
      if (!refreshed) return false;
      token = localStorage.getItem("accessToken");
    }

    // Always verify token with backend and update user data
    const userResponse = await axios.get(`${API_BASE_URL}/user/me/`, {
      headers: { Authorization: `Bearer ${token}` },
    });

    const userData = userResponse.data;
    localStorage.setItem("user", JSON.stringify(userData));

    return userData;
  } catch (error) {
    console.error("Authentication check failed:", error.response?.data || error.message);
    logout();
    return false;
  }
};

/**
 * Logout and clear storage
 */
export const logout = () => {
  localStorage.removeItem("accessToken");
  localStorage.removeItem("refreshToken");
  localStorage.removeItem("user");
};