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 { Email } from '../../../ts/mail/core/classes.email.js';
import * as net from 'net';

let testServer: ITestServer;

tap.test('setup test SMTP server', async () => {
  testServer = await startTestServer({
    port: 2570,
    tlsEnabled: false,
    authRequired: false
  });
  expect(testServer).toBeTruthy();
  expect(testServer.port).toEqual(2570);
});

tap.test('CEDGE-05: Mixed character encodings in email content', async () => {
  console.log('Testing mixed character encodings');
  
  const smtpClient = createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000,
    debug: true
  });

  // Email with mixed encodings
  const email = new Email({
    from: 'sender@example.com',
    to: ['recipient@example.com'],
    subject: 'Test with émojis 🎉 and spéçiål characters',
    text: 'Plain text with Unicode: café, naïve, 你好, مرحبا',
    html: '<p>HTML with entities: caf&eacute;, na&iuml;ve, and emoji 🌟</p>',
    attachments: [{
      filename: 'tëst-filé.txt',
      content: 'Attachment content with special chars: ñ, ü, ß'
    }]
  });

  const result = await smtpClient.sendMail(email);
  console.log(`Result: ${result.messageId ? 'Success' : 'Failed'}`);
  expect(result).toBeDefined();
  expect(result.messageId).toBeDefined();

  await smtpClient.close();
});

tap.test('CEDGE-05: Base64 encoding edge cases', async () => {
  console.log('Testing Base64 encoding edge cases');
  
  const smtpClient = createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000,
    debug: true
  });

  // Create various sizes of binary content
  const sizes = [0, 1, 2, 3, 57, 58, 59, 76, 77];  // Edge cases for base64 line wrapping
  
  for (const size of sizes) {
    const binaryContent = Buffer.alloc(size);
    for (let i = 0; i < size; i++) {
      binaryContent[i] = i % 256;
    }
    
    const email = new Email({
      from: 'sender@example.com',
      to: ['recipient@example.com'],
      subject: `Base64 test with ${size} bytes`,
      text: 'Testing base64 encoding',
      attachments: [{
        filename: `test-${size}.bin`,
        content: binaryContent
      }]
    });

    console.log(`  Testing with ${size} byte attachment...`);
    const result = await smtpClient.sendMail(email);
    expect(result).toBeDefined();
    expect(result.messageId).toBeDefined();
  }

  await smtpClient.close();
});

tap.test('CEDGE-05: Header encoding (RFC 2047)', async () => {
  console.log('Testing header encoding (RFC 2047)');
  
  const smtpClient = createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000,
    debug: true
  });

  // Test various header encodings
  const testCases = [
    {
      subject: 'Simple ASCII subject',
      from: 'john@example.com'
    },
    {
      subject: 'Subject with émojis 🎉 and spéçiål çhåracters',
      from: 'john@example.com'
    },
    {
      subject: 'Japanese: こんにちは, Chinese: 你好, Arabic: مرحبا',
      from: 'yamada@example.com'
    }
  ];

  for (const testCase of testCases) {
    console.log(`  Testing: "${testCase.subject.substring(0, 50)}..."`);
    
    const email = new Email({
      from: testCase.from,
      to: ['recipient@example.com'],
      subject: testCase.subject,
      text: 'Testing header encoding',
      headers: {
        'X-Custom': `Custom header with special chars: ${testCase.subject.substring(0, 20)}`
      }
    });

    const result = await smtpClient.sendMail(email);
    expect(result).toBeDefined();
    expect(result.messageId).toBeDefined();
  }

  await smtpClient.close();
});

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

export default tap.start();
