import { DirectConnection } from './DirectConnection.js';
import { ProxyConnection } from './ProxyConnection.js';
import { TunnelConnection } from './TunnelConnection.js';
/**
 * Manages different types of HTTP connections
 */
export class ConnectionManager {
    logger;
    stats;
    constructor(logger, stats) {
        this.logger = logger;
        this.stats = stats;
    }
    /**
     * Create a direct connection (HTTP or HTTPS)
     */
    createDirectConnection(options) {
        return new DirectConnection(options);
    }
    /**
     * Create a proxy connection for HTTP requests
     */
    createProxyConnection(options) {
        return new ProxyConnection(options);
    }
    /**
     * Create a tunnel connection for HTTPS requests through proxy
     */
    createTunnelConnection(options) {
        return new TunnelConnection(options);
    }
    /**
     * Determine the appropriate connection type and create it
     */
    createConnection(host, port, protocol, engineOptions) {
        const connectionOptions = {
            host,
            port,
            protocol,
            timeout: engineOptions.timeout,
            validateCertificates: engineOptions.validateCertificates,
            certificates: engineOptions.certificates,
            logger: this.logger,
            stats: this.stats,
        };
        // Direct connection
        if (!engineOptions.proxy) {
            this.logger.debug('Deciding to create a direct connection...');
            const directConnection = this.createDirectConnection(connectionOptions);
            return directConnection.connect();
        }
        // Proxy connection
        const proxyOptions = {
            ...connectionOptions,
            proxy: engineOptions.proxy,
            proxyIsSsl: engineOptions.proxy.startsWith('https:'),
            targetUrl: `${protocol}//${host}:${port}`,
            proxyUsername: engineOptions.proxyUsername,
            proxyPassword: engineOptions.proxyPassword,
            proxyAuthorization: engineOptions.proxyAuthorization,
        };
        // Check if we need a tunnel (HTTPS target through proxy)
        if (protocol === 'https:') {
            this.logger.debug('Deciding to create a tunnel connection through the proxy...');
            const tunnelOptions = {
                ...proxyOptions,
                targetHost: host,
                targetPort: port,
            };
            const tunnelConnection = this.createTunnelConnection(tunnelOptions);
            return tunnelConnection.connect();
        }
        this.logger.debug('Deciding to create a proxy connection...');
        const proxyConnection = this.createProxyConnection(proxyOptions);
        return proxyConnection.connect();
    }
}
//# sourceMappingURL=ConnectionManager.js.map