import { tap, expect } from '@git.zone/tstest/tapbundle';
import { createTestServer } from '../../helpers/server.loader.js';
import { createTestSmtpClient } from '../../helpers/smtp.client.js';
import { Email } from '../../../ts/mail/core/classes.email.js';

tap.test('CSEC-01: TLS Security Tests', async () => {
  console.log('\n🔒 Testing SMTP Client TLS Security');
  console.log('=' .repeat(60));

  // Test 1: Basic secure connection
  console.log('\nTest 1: Basic secure connection');
  const testServer1 = await createTestServer({});

  try {
    const smtpClient = createTestSmtpClient({
      host: testServer1.hostname,
      port: testServer1.port,
      secure: false // Using STARTTLS instead of direct TLS
    });

    const email = new Email({
      from: 'sender@example.com',
      to: ['recipient@example.com'],
      subject: 'TLS Test',
      text: 'Testing secure connection'
    });

    const result = await smtpClient.sendMail(email);
    console.log('  ✓ Email sent over secure connection');
    expect(result).toBeDefined();

  } finally {
    testServer1.server.close();
  }

  // Test 2: Connection with security options
  console.log('\nTest 2: Connection with TLS options');
  const testServer2 = await createTestServer({});

  try {
    const smtpClient = createTestSmtpClient({
      host: testServer2.hostname,
      port: testServer2.port,
      secure: false,
      tls: {
        rejectUnauthorized: false // Accept self-signed for testing
      }
    });

    const verified = await smtpClient.verify();
    console.log('  ✓ TLS connection established with custom options');
    expect(verified).toBeDefined();

  } finally {
    testServer2.server.close();
  }

  // Test 3: Multiple secure emails
  console.log('\nTest 3: Multiple secure emails');
  const testServer3 = await createTestServer({});

  try {
    const smtpClient = createTestSmtpClient({
      host: testServer3.hostname,
      port: testServer3.port
    });

    for (let i = 0; i < 3; i++) {
      const email = new Email({
        from: 'sender@secure.com',
        to: [`recipient${i}@secure.com`],
        subject: `Secure Email ${i + 1}`,
        text: 'Testing TLS security'
      });

      const result = await smtpClient.sendMail(email);
      console.log(`  ✓ Secure email ${i + 1} sent`);
      expect(result).toBeDefined();
    }

  } finally {
    testServer3.server.close();
  }

  console.log('\n✅ CSEC-01: TLS security tests completed');
});

tap.start();