/**
 * auth.js - Authentication wrapper for GraphTalker
 *
 * This script monkey-patches fetch() to automatically add authentication
 * headers, so the existing app.js code works unchanged.
 *
 * Load this BEFORE app.js in index.html.
 */

(function() {
    'use strict';

    // Skip auth if SKIP_AUTH is set (standalone mode)
    if (window.SKIP_AUTH) {
        console.log('Auth: Skipping authentication (SKIP_AUTH=true)');
        document.addEventListener('DOMContentLoaded', function() {
            ['logout-btn', 'admin-link'].forEach(function(id) {
                var el = document.getElementById(id);
                if (el) el.remove();
            });
        });
        return;
    }

    // Get token from localStorage
    var authToken = localStorage.getItem('authToken');
    var originalFetch = window.fetch;

    // Redirect to login if no token (except on login page)
    if (!authToken && !window.location.pathname.includes('login')) {
        console.log('Auth: No token, redirecting to login');
        window.location.href = '/login.html';
        return;
    }

    /**
     * Wrap fetch to automatically add Authorization header
     */
    window.fetch = function(url, options) {
        options = options || {};

        // Don't add auth to login endpoint (it doesn't need it)
        if (typeof url === 'string' && url === '/auth/login') {
            return originalFetch.call(this, url, options);
        }

        // Add Authorization header if we have a token
        if (authToken) {
            // Create headers object if needed
            if (!options.headers) {
                options.headers = {};
            }

            // Handle both Headers object and plain object
            if (options.headers instanceof Headers) {
                options.headers.set('Authorization', 'Bearer ' + authToken);
            } else {
                options.headers['Authorization'] = 'Bearer ' + authToken;
            }
        }

        // Call original fetch and handle 401 responses
        return originalFetch.call(this, url, options).then(function(response) {
            if (response.status === 401) {
                console.log('Auth: Received 401, clearing token and redirecting to login');
                localStorage.removeItem('authToken');
                window.location.href = '/login.html';
            }
            return response;
        });
    };

    /**
     * Wrap EventSource for SSE streaming with auth
     */
    var OriginalEventSource = window.EventSource;
    window.EventSource = function(url, options) {
        // Add token as query parameter for EventSource (can't set headers)
        if (authToken && url.indexOf('token=') === -1) {
            var separator = url.indexOf('?') === -1 ? '?' : '&';
            url = url + separator + 'token=' + encodeURIComponent(authToken);
        }
        return new OriginalEventSource(url, options);
    };
    // Copy static properties
    window.EventSource.CONNECTING = OriginalEventSource.CONNECTING;
    window.EventSource.OPEN = OriginalEventSource.OPEN;
    window.EventSource.CLOSED = OriginalEventSource.CLOSED;

    /**
     * Logout function - clears token and redirects to login
     */
    window.logout = async function() {
        try {
            // Tell server to kill our eval-server
            await originalFetch('/auth/logout', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + authToken
                }
            });
        } catch(e) {
            console.error('Auth: Logout request failed:', e);
        }

        // Clear token and redirect regardless of server response
        localStorage.removeItem('authToken');
        window.location.href = '/login.html';
    };

    /**
     * Get current user info
     */
    window.getCurrentUser = async function() {
        try {
            var response = await fetch('/auth/me');
            if (response.ok) {
                return await response.json();
            }
        } catch(e) {
            console.error('Auth: Failed to get user info:', e);
        }
        return null;
    };

    /**
     * Check if current user is superuser
     */
    window.isSuperuser = async function() {
        var user = await window.getCurrentUser();
        return user && user.role === 'superuser';
    };

    console.log('Auth: Initialized with token');
})();
