import axios from "axios";

const API_URL = "/api";

// Helper function to refresh tokens
export const refreshAccessToken = async () => {
    try {
        const refreshToken = localStorage.getItem("refresh_token");
        if (!refreshToken) throw new Error("No refresh token available");

        const response = await axios.post(`${API_URL}/auth/token/refresh/`, {
            refresh: refreshToken,
        });

        const newAccessToken = response.data.access;
        const newRefreshToken = response.data.refresh || refreshToken; // Update if rotated

        localStorage.setItem("access_token", newAccessToken);
        localStorage.setItem("refresh_token", newRefreshToken);

        return newAccessToken;
    } catch (error) {
        console.error("Failed to refresh token:", error);
        logout(); // Log out if refresh fails
        return null;
    }
};

// Login function
export const login = async (username: string, password: string) => {
    const response = await axios.post(`${API_URL}/auth/token/`, { username, password });
    localStorage.setItem("access_token", response.data.access);
    localStorage.setItem("refresh_token", response.data.refresh);
    return response.data;
};

// Logout function
export const logout = () => {
    // Store the current path before redirecting to login
    localStorage.setItem("redirect_after_login", window.location.pathname);

    // Clear tokens and redirect to login page
    localStorage.removeItem("access_token");
    localStorage.removeItem("refresh_token");
    window.location.href = "/user/login"; // Redirect to login page
};

// Get stored access token
export const getAccessToken = () => {
    return localStorage.getItem("access_token");
};

// Export API_URL for consistency
export { API_URL };
