"use strict";
/**
 * useAuth Hook
 * Manages authentication state, tokens, and user sessions
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAuth = void 0;
const react_1 = require("react");
const react_query_1 = require("@tanstack/react-query");
const useApi_1 = require("./useApi");
const useAuth = () => {
    const api = (0, useApi_1.useApi)();
    const queryClient = (0, react_query_1.useQueryClient)();
    const [authState, setAuthState] = (0, react_1.useState)({
        user: null,
        isAuthenticated: false,
        isLoading: true,
    });
    // Check session on mount
    (0, react_1.useEffect)(() => {
        checkSession();
    }, []);
    // Session check query
    const { refetch: checkSession } = (0, react_query_1.useQuery)({
        queryKey: ['auth', 'session'],
        queryFn: async () => {
            try {
                const response = await api.get('/auth/session', {
                    skipErrorHandling: true,
                });
                setAuthState({
                    user: response.data.user,
                    isAuthenticated: true,
                    isLoading: false,
                });
                return response.data;
            }
            catch (error) {
                setAuthState({
                    user: null,
                    isAuthenticated: false,
                    isLoading: false,
                });
                throw error;
            }
        },
        retry: false,
        enabled: false,
    });
    // Login mutation
    const loginMutation = (0, react_query_1.useMutation)({
        mutationFn: async (credentials) => {
            const response = await api.post('/auth/login', credentials);
            const { user, token, refreshToken } = response.data;
            // Store tokens
            localStorage.setItem('token', token);
            localStorage.setItem('refreshToken', refreshToken);
            setAuthState({
                user,
                isAuthenticated: true,
                isLoading: false,
            });
            return response.data;
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['auth'] });
        },
    });
    // Logout mutation
    const logoutMutation = (0, react_query_1.useMutation)({
        mutationFn: async () => {
            try {
                await api.post('/auth/logout', null, { skipErrorHandling: true });
            }
            finally {
                // Clear local storage and state
                localStorage.removeItem('token');
                localStorage.removeItem('refreshToken');
                setAuthState({
                    user: null,
                    isAuthenticated: false,
                    isLoading: false,
                });
                queryClient.clear();
            }
        },
    });
    // Get current token
    const getToken = (0, react_1.useCallback)(async () => {
        const token = localStorage.getItem('token');
        if (!token)
            return null;
        // Check if token is expired
        try {
            const payload = JSON.parse(atob(token.split('.')[1]));
            if (payload.exp * 1000 < Date.now()) {
                // Token expired, try to refresh
                const refreshToken = localStorage.getItem('refreshToken');
                if (refreshToken) {
                    try {
                        const response = await api.post('/auth/refresh', {
                            refreshToken,
                        });
                        const { token: newToken, refreshToken: newRefreshToken } = response.data;
                        localStorage.setItem('token', newToken);
                        localStorage.setItem('refreshToken', newRefreshToken);
                        return newToken;
                    }
                    catch (error) {
                        // Refresh failed, logout
                        await logout();
                        return null;
                    }
                }
                return null;
            }
            return token;
        }
        catch (error) {
            return null;
        }
    }, [api]);
    // Login handler
    const login = (0, react_1.useCallback)(async (credentials) => {
        return loginMutation.mutateAsync(credentials);
    }, [loginMutation]);
    // Logout handler
    const logout = (0, react_1.useCallback)(async () => {
        return logoutMutation.mutateAsync();
    }, [logoutMutation]);
    return {
        ...authState,
        login,
        logout,
        getToken,
        checkSession,
    };
};
exports.useAuth = useAuth;
exports.default = exports.useAuth;
//# sourceMappingURL=useAuth.js.map