import { tap, expect } from '@git.zone/tstest/tapbundle';
import { startTestServer, stopTestServer, type ITestServer } from '../../helpers/server.loader.js';
import { connectToSmtp, performSmtpHandshake, closeSmtpConnection } from '../../helpers/utils.js';

let testServer: ITestServer;

tap.test('setup - start SMTP server with TLS support', async () => {
  testServer = await startTestServer({
    port: 2525,
    tlsEnabled: true  // Enable TLS support
  });
  
  await new Promise(resolve => setTimeout(resolve, 1000));
  expect(testServer.port).toEqual(2525);
});

tap.test('CM-01: TLS Connection Test - server should advertise STARTTLS capability', async () => {
  const startTime = Date.now();
  
  try {
    // Connect to SMTP server
    const socket = await connectToSmtp(testServer.hostname, testServer.port);
    expect(socket).toBeInstanceOf(Object);
    
    // Perform handshake and get capabilities
    const capabilities = await performSmtpHandshake(socket, 'test.example.com');
    expect(capabilities).toBeArray();
    
    // Check for STARTTLS support
    const supportsStarttls = capabilities.some(cap => cap.toUpperCase().includes('STARTTLS'));
    expect(supportsStarttls).toEqual(true);
    
    // Close connection gracefully
    await closeSmtpConnection(socket);
    
    const duration = Date.now() - startTime;
    console.log(`✅ TLS capability test completed in ${duration}ms`);
    console.log(`📋 Server capabilities: ${capabilities.join(', ')}`);
    
  } catch (error) {
    const duration = Date.now() - startTime;
    console.error(`❌ TLS connection test failed after ${duration}ms:`, error);
    throw error;
  }
});

tap.test('CM-01: TLS Connection Test - verify TLS certificate configuration', async () => {
  // This test verifies that the server has TLS certificates configured
  expect(testServer.config.tlsEnabled).toEqual(true);
  
  // The server should have loaded certificates during startup
  // In production, this would validate actual certificate properties
  console.log('✅ TLS configuration verified');
});

tap.test('cleanup - stop SMTP server', async () => {
  await stopTestServer(testServer);
  console.log('✅ Test server stopped');
});

export default tap.start();