/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import * as http from 'node:http';
import * as url from 'node:url';
import { SixthUserCache } from './sixthUserCache.js';
import { SubscriptionManager } from './subscriptionManager.js';
import { debugLogger } from '../utils/debugLogger.js';
export class SixthAuthServer {
    server = null;
    port;
    config;
    constructor(config) {
        this.config = config;
        this.port = config.callbackPort;
    }
    /**
     * Start the callback server and return a promise that resolves with user info
     */
    async startAndWaitForAuth() {
        return new Promise((resolve, reject) => {
            this.server = http.createServer((req, res) => {
                this.handleRequest(req, res, resolve, reject);
            });
            // Try to start on the preferred port, or find an available one
            this.tryStartServer(resolve, reject);
        });
    }
    tryStartServer(resolve, reject, attempts = 0) {
        if (attempts > 10) {
            reject(new Error('Could not find an available port for auth callback'));
            return;
        }
        const currentPort = this.port + attempts;
        this.server.listen(currentPort, () => {
            this.port = currentPort;
            debugLogger.log(`Auth callback server started on port ${this.port}`);
        });
        this.server.on('error', (error) => {
            if (error.code === 'EADDRINUSE') {
                debugLogger.log(`Port ${currentPort} is busy, trying next port`);
                this.tryStartServer(resolve, reject, attempts + 1);
            }
            else {
                reject(error);
            }
        });
    }
    async handleRequest(req, res, resolve, reject) {
        try {
            const parsedUrl = url.parse(req.url || '', true);
            const token = parsedUrl.query['token'];
            if (!token) {
                this.sendErrorPage(res, 'No authentication token received');
                reject(new Error('No authentication token received'));
                return;
            }
            // Validate token with Sixth API
            const userInfo = await this.validateToken(token);
            // Cache user info and JWT token for future re-authentication
            await SixthUserCache.cacheUserInfo(userInfo);
            await SubscriptionManager.cacheJWT(token);
            // Send success page
            this.sendSuccessPage(res, userInfo);
            // Close server after a short delay
            setTimeout(() => {
                this.stop();
            }, 2000);
            resolve(userInfo);
        }
        catch (error) {
            debugLogger.error('Auth callback error:', error);
            this.sendErrorPage(res, 'Authentication failed');
            reject(error instanceof Error ? error : new Error('Authentication failed'));
        }
    }
    async validateToken(token) {
        const response = await fetch(this.config.apiUrl, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json',
            },
        });
        if (!response.ok) {
            throw new Error(`Authentication failed: ${response.statusText}`);
        }
        const userInfo = await response.json();
        // Validate required fields
        if (!userInfo.id || !userInfo.email || !userInfo.fullname) {
            throw new Error('Invalid user information received');
        }
        return userInfo;
    }
    sendSuccessPage(res, userInfo) {
        const html = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sixth CLI - Authentication Successful</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
        }
        
        .container {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 3rem;
            text-align: center;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            max-width: 500px;
            width: 90%;
        }
        
        .logo {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 1rem;
            color: #fff;
        }
        
        .success-icon {
            font-size: 4rem;
            margin-bottom: 1rem;
            color: #4ade80;
        }
        
        h1 {
            font-size: 1.8rem;
            margin-bottom: 1rem;
            color: #fff;
        }
        
        .user-info {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 12px;
            padding: 1.5rem;
            margin: 1.5rem 0;
            text-align: left;
        }
        
        .user-info div {
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
        }
        
        .user-info strong {
            color: #fff;
        }
        
        .message {
            font-size: 1rem;
            margin-bottom: 1.5rem;
            opacity: 0.9;
        }
        
        .close-message {
            font-size: 0.9rem;
            opacity: 0.7;
            font-style: italic;
        }
        
        .status {
            display: inline-block;
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
            margin-left: 0.5rem;
        }
        
        .subscriber {
            background: #4ade80;
            color: #1f2937;
        }
        
        .non-subscriber {
            background: #fbbf24;
            color: #1f2937;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">SIXTH</div>
        <div class="success-icon">✅</div>
        <h1>Authentication Successful!</h1>
        
        <div class="user-info">
            <div><strong>Name:</strong> ${userInfo.fullname}</div>
            <div><strong>Email:</strong> ${userInfo.email}</div>
            <div><strong>Company:</strong> ${userInfo.company_name}</div>
            <div>
                <strong>Status:</strong>
                <span class="status ${userInfo.subscriber ? 'subscriber' : 'non-subscriber'}">
                    ${userInfo.subscriber ? 'Subscriber' : 'Free User'}
                </span>
            </div>
        </div>
        
        <div class="message">
            Welcome to Sixth CLI! You can now return to your terminal.
        </div>
        
        <div class="close-message">
            This window will close automatically in a few seconds...
        </div>
    </div>
    
    <script>
        setTimeout(() => {
            window.close();
        }, 3000);
    </script>
</body>
</html>`;
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(html);
    }
    sendErrorPage(res, message) {
        const html = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sixth CLI - Authentication Error</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
        }
        
        .container {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 3rem;
            text-align: center;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            max-width: 500px;
            width: 90%;
        }
        
        .logo {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 1rem;
            color: #fff;
        }
        
        .error-icon {
            font-size: 4rem;
            margin-bottom: 1rem;
            color: #fca5a5;
        }
        
        h1 {
            font-size: 1.8rem;
            margin-bottom: 1rem;
            color: #fff;
        }
        
        .message {
            font-size: 1rem;
            margin-bottom: 1.5rem;
            opacity: 0.9;
        }
        
        .close-message {
            font-size: 0.9rem;
            opacity: 0.7;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">SIXTH</div>
        <div class="error-icon">❌</div>
        <h1>Authentication Failed</h1>
        
        <div class="message">
            ${message}
        </div>
        
        <div class="close-message">
            Please try again from your terminal.
        </div>
    </div>
</body>
</html>`;
        res.writeHead(400, { 'Content-Type': 'text/html' });
        res.end(html);
    }
    getCallbackUrl() {
        return `http://localhost:${this.port}`;
    }
    stop() {
        if (this.server) {
            this.server.close();
            this.server = null;
            debugLogger.log('Auth callback server stopped');
        }
    }
}
//# sourceMappingURL=sixthAuthServer.js.map