import { tap, expect } from '@git.zone/tstest/tapbundle';
import { startTestServer, stopTestServer, type ITestServer } from '../../helpers/server.loader.js';
import { createSmtpClient } from '../../../ts/mail/delivery/smtpclient/index.js';
import type { SmtpClient } from '../../../ts/mail/delivery/smtpclient/smtp-client.js';
import { Email } from '../../../ts/mail/core/classes.email.js';

let testServer: ITestServer;
let smtpClient: SmtpClient;

tap.test('setup - start SMTP server with TLS', async () => {
  testServer = await startTestServer({
    port: 2526,
    tlsEnabled: true,
    authRequired: false
  });
  
  expect(testServer.port).toEqual(2526);
  expect(testServer.config.tlsEnabled).toBeTrue();
});

tap.test('CCM-02: TLS Connection - should establish secure connection via STARTTLS', async () => {
  const startTime = Date.now();
  
  try {
    // Create SMTP client with STARTTLS (not direct TLS)
    smtpClient = createSmtpClient({
      host: testServer.hostname,
      port: testServer.port,
      secure: false, // Start with plain connection
      connectionTimeout: 10000,
      tls: {
        rejectUnauthorized: false // For self-signed test certificates
      },
      debug: true
    });
    
    // Verify connection (will upgrade to TLS via STARTTLS)
    const isConnected = await smtpClient.verify();
    expect(isConnected).toBeTrue();
    
    const duration = Date.now() - startTime;
    console.log(`✅ STARTTLS connection established in ${duration}ms`);
    
  } catch (error) {
    const duration = Date.now() - startTime;
    console.error(`❌ STARTTLS connection failed after ${duration}ms:`, error);
    throw error;
  }
});

tap.test('CCM-02: TLS Connection - should send email over secure connection', async () => {
  const email = new Email({
    from: 'test@example.com',
    to: 'recipient@example.com',
    subject: 'TLS Connection Test',
    text: 'This email was sent over a secure TLS connection',
    html: '<p>This email was sent over a <strong>secure TLS connection</strong></p>'
  });
  
  const result = await smtpClient.sendMail(email);
  
  expect(result).toBeTruthy();
  expect(result.success).toBeTrue();
  expect(result.messageId).toBeTruthy();
  
  console.log(`✅ Email sent over TLS with message ID: ${result.messageId}`);
});

tap.test('CCM-02: TLS Connection - should reject invalid certificates when required', async () => {
  // Create new client with strict certificate validation
  const strictClient = createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    tls: {
      rejectUnauthorized: true // Strict validation
    }
  });
  
  // Should fail with self-signed certificate
  const result = await strictClient.verify();
  expect(result).toBeFalse();
  
  console.log('✅ Correctly rejected self-signed certificate with strict validation');
  
  await strictClient.close();
});

tap.test('CCM-02: TLS Connection - should work with direct TLS if supported', async () => {
  // Try direct TLS connection (might fail if server doesn't support it)
  const directTlsClient = createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: true, // Direct TLS from start
    connectionTimeout: 5000,
    tls: {
      rejectUnauthorized: false
    }
  });
  
  const result = await directTlsClient.verify();
  
  if (result) {
    console.log('✅ Direct TLS connection supported and working');
  } else {
    console.log('ℹ️ Direct TLS not supported, STARTTLS is the way');
  }
  
  await directTlsClient.close();
});

tap.test('CCM-02: TLS Connection - should verify TLS cipher suite', async () => {
  // Send email and check connection details
  const email = new Email({
    from: 'cipher-test@example.com',
    to: 'recipient@example.com',
    subject: 'TLS Cipher Test',
    text: 'Testing TLS cipher suite'
  });
  
  // The actual cipher info would be in debug logs
  console.log('ℹ️ TLS cipher information available in debug logs');
  
  const result = await smtpClient.sendMail(email);
  expect(result.success).toBeTrue();
  
  console.log('✅ Email sent successfully over encrypted connection');
});

tap.test('cleanup - close SMTP client', async () => {
  if (smtpClient) {
    await smtpClient.close();
  }
});

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

export default tap.start();