// Admin login routes with API key support
const express = require('express');
const router = express.Router();
const config = require('../config/environment');
const { auditLog } = require('../utils/logging');

// Admin login page with API key support
router.get('/login', (req, res) => {
    res.send(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Admin Login - QuickBooks Payment Gateway</title>
            <style>
                body { 
                    font-family: Arial, sans-serif; 
                    display: flex; 
                    justify-content: center; 
                    align-items: center; 
                    height: 100vh; 
                    margin: 0; 
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                }
                .login-container {
                    background: white;
                    padding: 40px;
                    border-radius: 12px;
                    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
                    width: 100%;
                    max-width: 400px;
                }
                .logo {
                    text-align: center;
                    margin-bottom: 30px;
                }
                .logo h1 {
                    color: #333;
                    margin: 0;
                    font-size: 24px;
                }
                .logo p {
                    color: #666;
                    margin: 5px 0 0 0;
                    font-size: 14px;
                }
                .form-group {
                    margin-bottom: 20px;
                }
                .form-group label {
                    display: block;
                    margin-bottom: 8px;
                    color: #333;
                    font-weight: bold;
                }
                .form-group input {
                    width: 100%;
                    padding: 12px;
                    border: 2px solid #ddd;
                    border-radius: 6px;
                    font-size: 16px;
                    transition: border-color 0.3s;
                    box-sizing: border-box;
                }
                .form-group input:focus {
                    outline: none;
                    border-color: #007cba;
                }
                .login-btn {
                    width: 100%;
                    padding: 12px;
                    background: linear-gradient(135deg, #007cba, #005a87);
                    color: white;
                    border: none;
                    border-radius: 6px;
                    font-size: 16px;
                    font-weight: bold;
                    cursor: pointer;
                    transition: transform 0.2s;
                }
                .login-btn:hover {
                    transform: translateY(-2px);
                }
                .login-btn:active {
                    transform: translateY(0);
                }
                .error {
                    background: #f8d7da;
                    color: #721c24;
                    padding: 10px;
                    border-radius: 4px;
                    margin-bottom: 20px;
                    display: none;
                }
                .success {
                    background: #d4edda;
                    color: #155724;
                    padding: 10px;
                    border-radius: 4px;
                    margin-bottom: 20px;
                    display: none;
                }
            </style>
        </head>
        <body>
            <div class="login-container">
                <div class="logo">
                    <h1>🏢 Admin Login</h1>
                    <p>QuickBooks Payment Gateway</p>
                </div>
                
                <div id="error-message" class="error"></div>
                <div id="success-message" class="success"></div>
                
                <!-- API Key Method -->
                <div id="api-method" class="method active">
                    <form id="api-login-form">
                        <div class="form-group">
                            <label for="api-key">🔑 Admin API Key</label>
                            <input type="password" id="api-key" name="apiKey" placeholder="Enter your admin API key" required>
                        </div>
                        <button type="submit" class="login-btn">Login with API Key</button>
                    </form>
                </div>
                
                
            </div>
            
            <script>
                
                function showError(message) {
                    const errorDiv = document.getElementById('error-message');
                    errorDiv.textContent = message;
                    errorDiv.style.display = 'block';
                    document.getElementById('success-message').style.display = 'none';
                }
                
                function showSuccess(message) {
                    const successDiv = document.getElementById('success-message');
                    successDiv.textContent = message;
                    successDiv.style.display = 'block';
                    document.getElementById('error-message').style.display = 'none';
                }
                
                function clearMessages() {
                    document.getElementById('error-message').style.display = 'none';
                    document.getElementById('success-message').style.display = 'none';
                }
                
                // API Key Login
                document.getElementById('api-login-form').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    clearMessages();
                    
                    const apiKey = document.getElementById('api-key').value;
                    
                    try {
                        const response = await fetch('/admin/api-login', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ apiKey })
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            showSuccess('Login successful! Redirecting...');
                            sessionStorage.setItem('adminApiKey', apiKey);
                            setTimeout(() => {
                                window.location.href = '/admin/dashboard';
                            }, 1000);
                        } else {
                            showError(result.message || 'Invalid API key');
                        }
                    } catch (error) {
                        showError('Connection error. Please try again.');
                    }
                });
                
            </script>
        </body>
        </html>
    `);
});


// API Key authentication endpoint
router.post('/api-login', (req, res) => {
    const { apiKey } = req.body;
    
    
    if (!apiKey || apiKey !== config.ADMIN_API_KEY) {
        auditLog('ADMIN_API_LOGIN_FAILED', { 
            providedKey: apiKey ? 'provided' : 'missing',
            ip: req.ip,
            userAgent: req.get('User-Agent')
        }, req);
        
        return res.status(401).json({
            success: false,
            message: 'Invalid API key'
        });
    }
    
    auditLog('ADMIN_API_LOGIN_SUCCESS', { ip: req.ip }, req);
    
    res.json({
        success: true,
        message: 'Authentication successful'
    });
});


module.exports = router;
