/**
 * AniWorld - Authentication Module
 *
 * Handles user authentication, token management,
 * and session validation.
 *
 * Dependencies: constants.js
 */

var AniWorld = window.AniWorld || {};

AniWorld.Auth = (function() {
    'use strict';

    const STORAGE = AniWorld.Constants.STORAGE_KEYS;
    const API = AniWorld.Constants.API;

    /**
     * Get the stored access token
     * @returns {string|null} The access token or null if not found
     */
    function getToken() {
        return localStorage.getItem(STORAGE.ACCESS_TOKEN);
    }

    /**
     * Store the access token
     * @param {string} token - The access token to store
     */
    function setToken(token) {
        localStorage.setItem(STORAGE.ACCESS_TOKEN, token);
    }

    /**
     * Remove the stored access token
     */
    function removeToken() {
        localStorage.removeItem(STORAGE.ACCESS_TOKEN);
        localStorage.removeItem(STORAGE.TOKEN_EXPIRES_AT);
    }

    /**
     * Get authorization headers for API requests
     * @returns {Object} Headers object with Authorization if token exists
     */
    function getAuthHeaders() {
        const token = getToken();
        return token ? { 'Authorization': 'Bearer ' + token } : {};
    }

    /**
     * Check if user is authenticated
     * Redirects to login page if not authenticated
     * @returns {Promise<boolean>} True if authenticated, false otherwise
     */
    async function checkAuth() {
        const currentPath = window.location.pathname;
        
        // Don't check authentication if already on login or setup pages
        if (currentPath === '/login' || currentPath === '/setup') {
            return false;
        }

        try {
            const token = getToken();
            console.log('checkAuthentication: token exists =', !!token);
            
            if (!token) {
                console.log('checkAuthentication: No token found, redirecting to /login');
                window.location.href = '/login';
                return false;
            }
            
            const headers = {
                'Authorization': 'Bearer ' + token
            };
            
            const response = await fetch(API.AUTH_STATUS, { headers });
            console.log('checkAuthentication: response status =', response.status);
            
            if (!response.ok) {
                console.log('checkAuthentication: Response not OK, status =', response.status);
                throw new Error('HTTP ' + response.status);
            }
            
            const data = await response.json();
            console.log('checkAuthentication: data =', data);

            if (!data.configured) {
                console.log('checkAuthentication: Not configured, redirecting to /setup');
                window.location.href = '/setup';
                return false;
            }

            if (!data.authenticated) {
                console.log('checkAuthentication: Not authenticated, redirecting to /login');
                removeToken();
                window.location.href = '/login';
                return false;
            }

            console.log('checkAuthentication: Authenticated successfully');
            
            // Show logout button if it exists
            const logoutBtn = document.getElementById('logout-btn');
            if (logoutBtn) {
                logoutBtn.style.display = 'block';
            }
            
            return true;
        } catch (error) {
            console.error('Authentication check failed:', error);
            removeToken();
            window.location.href = '/login';
            return false;
        }
    }

    /**
     * Log out the current user
     * @param {Function} showToast - Optional function to show toast messages
     */
    async function logout(showToast) {
        try {
            const response = await AniWorld.ApiClient.request(API.AUTH_LOGOUT, { method: 'POST' });
            
            removeToken();

            if (response && response.ok) {
                const data = await response.json();
                if (showToast) {
                    showToast(data.status === 'ok' ? 'Logged out successfully' : 'Logged out', 'success');
                }
            } else {
                if (showToast) {
                    showToast('Logged out', 'success');
                }
            }
            
            setTimeout(function() {
                window.location.href = '/login';
            }, 1000);
        } catch (error) {
            console.error('Logout error:', error);
            removeToken();
            if (showToast) {
                showToast('Logged out', 'success');
            }
            setTimeout(function() {
                window.location.href = '/login';
            }, 1000);
        }
    }

    /**
     * Check if user has a valid token stored
     * @returns {boolean} True if token exists
     */
    function hasToken() {
        return !!getToken();
    }

    // Public API
    return {
        getToken: getToken,
        setToken: setToken,
        removeToken: removeToken,
        getAuthHeaders: getAuthHeaders,
        checkAuth: checkAuth,
        logout: logout,
        hasToken: hasToken
    };
})();
