<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vault URL Lookup</title>
    <style>
        /* CSS uses standard hex colors now! */
        body { font-family: Arial, sans-serif; background-color: #f4f7f6; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
        .container { background: white; padding: 30px; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); width: 100%; max-width: 600px; text-align: center; }
        input { width: 80%; padding: 10px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px; font-size: 16px; }
        button { background-color: #000; color: white; border: none; padding: 10px 20px; font-size: 16px; border-radius: 4px; cursor: pointer; }
        button:hover { background-color: #333; }
        p {  }
        .info { margin-left: 40px; margin-right: 40px; margin-top: 15px; margin-bottom: 15px; background-color: #f2efef; color: #000000; border: 1px solid #686868; }
        .info-title { color: #247800; }
        .info-body { font-style: italic; font-size: 14px; line-height: 1.6; white-space: pre-line; text-align: left; padding-left: 10px; padding-right: 10px; }
        .result { margin-top: 20px; padding: 15px; border-radius: 4px; display: none; word-wrap: break-word; }
        .success { background-color: #e8f5e9; color: #2e7d32; border: 1px solid #c8e6c9; }
        .fallback { background-color: #fff3e0; color: #ef6c00; border: 1px solid #ffe0b2; }
    </style>
</head>
<body>
    <div class="container">
        <h2>Where is my namespace?</h2>
        <div class="info">
            <p class="info-title">Vault / Openbao migration in progress...</p>
            <p class="info-body">During this period, to access the UI, please enter your namespace name to get the UI URL.
                API calls are automatically routed to the correct backend (Vault or Openbao), depending on the namespace.
                The migration date of your namespace can be viewed in MCC Vault.
                For more information, please visit <a href="https://adeogroup.atlassian.net/wiki/spaces/SOFA/pages/467568736/Vault+-+Migration">Vault Migration</a>.</p>
        </div>
        <input type="text" id="namespaceInput" placeholder="Enter your namespace..." oninput="debouncedSearch()" onkeypress="handleEnter(event)">
        <br>
        <button onclick="findUrl()">Search</button>
        <div id="resultBox" class="result"></div>
    </div>

    <script>
        let timeoutId; // Variable pour le debounce

        // Écouteur au chargement de la page pour la redirection automatique
        window.addEventListener('DOMContentLoaded', () => {
            const urlParams = new URLSearchParams(window.location.search);
            const namespaceFromUrl = urlParams.get('namespace');
            
            if (namespaceFromUrl) {
                // Remplir l'input pour un meilleur retour visuel
                document.getElementById('namespaceInput').value = namespaceFromUrl;
                // Lancer la redirection automatique
                autoRedirect(namespaceFromUrl);
            }
        });

        // Fonction spécifique pour la redirection silencieuse
        async function autoRedirect(ns) {
            const resultBox = document.getElementById('resultBox');
            resultBox.style.display = 'block';
            resultBox.className = 'result fallback';
            resultBox.innerHTML = 'Redirecting to your namespace...';

            try {
                const response = await fetch(`/api/get-vault-url?namespace=${encodeURIComponent(ns)}`);
                if (!response.ok) throw new Error("API error");
                
                const data = await response.json();
                const targetUrl = `${data.url}/ui/vault/auth?namespace=${encodeURIComponent(ns)}&with=oidc`;
                
                // Redirection vers l'URL (remplace l'entrée dans l'historique)
                window.location.replace(targetUrl);
            } catch (err) {
                resultBox.className = 'result fallback';
                resultBox.innerHTML = 'Error during automatic redirection. Please try manually.';
            }
        }

        // Fonction anti-rebond : attend 500ms après la dernière frappe pour lancer la recherche
        function debouncedSearch() {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => {
                findUrl();
            }, 500); 
        }

        // Permet de forcer la recherche immédiate si l'utilisateur appuie sur Entrée
        function handleEnter(e) { 
            if (e.key === 'Enter') {
                clearTimeout(timeoutId);
                findUrl(); 
            }
        }

        // Fonction de recherche manuelle
        async function findUrl() {
            const ns = document.getElementById('namespaceInput').value.trim();
            const resultBox = document.getElementById('resultBox');

            if (!ns) {
                resultBox.style.display = 'block';
                resultBox.className = 'result fallback';
                resultBox.innerHTML = 'Please enter a namespace.';
                return;
            }

            try {
                // Appel à l'API NGINX
                const response = await fetch(`/api/get-vault-url?namespace=${encodeURIComponent(ns)}`);
                const data = await response.json();

                resultBox.style.display = 'block';
                resultBox.className = 'result success';
                resultBox.innerHTML = `<strong>Your namespace is at:</strong><br><a href="${data.url}/ui/vault/auth?namespace=${encodeURIComponent(ns)}&with=oidc" target="_blank">${data.url}</a>`;
            } catch (err) {
                resultBox.style.display = 'block';
                resultBox.className = 'result fallback';
                resultBox.innerHTML = 'Error communicating with the NGINX server.';
            }
        }
    </script>
</body>
</html>

