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';

tap.test('setup - start SMTP server for network efficiency tests', async () => {
  // Just a placeholder to ensure server starts properly
});

tap.test('CPERF-05: network efficiency - connection reuse', async () => {
  const testServer = await startTestServer({
    port: 2525,
    tlsEnabled: false,
    authRequired: false
  });

  console.log('Testing connection reuse efficiency...');
  
  // Test 1: Individual connections (2 messages)
  console.log('Sending 2 messages with individual connections...');
  const individualStart = Date.now();
  
  for (let i = 0; i < 2; i++) {
    const client = createSmtpClient({
      host: 'localhost',
      port: 2525,
      secure: false
    });

    const email = new Email({
      from: 'sender@example.com',
      to: [`recipient${i}@example.com`],
      subject: `Test ${i}`,
      text: `Message ${i}`,
    });

    const result = await client.sendMail(email);
    expect(result.success).toBeTrue();
    await client.close();
  }
  
  const individualTime = Date.now() - individualStart;
  console.log(`Individual connections: 2 connections, ${individualTime}ms`);

  // Test 2: Connection reuse (2 messages)
  console.log('Sending 2 messages with connection reuse...');
  const reuseStart = Date.now();
  
  const reuseClient = createSmtpClient({
    host: 'localhost',
    port: 2525,
    secure: false
  });

  for (let i = 0; i < 2; i++) {
    const email = new Email({
      from: 'sender@example.com',
      to: [`reuse${i}@example.com`],
      subject: `Reuse ${i}`,
      text: `Message ${i}`,
    });

    const result = await reuseClient.sendMail(email);
    expect(result.success).toBeTrue();
  }
  
  await reuseClient.close();
  
  const reuseTime = Date.now() - reuseStart;
  console.log(`Connection reuse: 1 connection, ${reuseTime}ms`);
  
  // Connection reuse should complete reasonably quickly
  expect(reuseTime).toBeLessThan(5000); // Less than 5 seconds

  await stopTestServer(testServer);
});

tap.test('CPERF-05: network efficiency - message throughput', async () => {
  const testServer = await startTestServer({
    port: 2525,
    tlsEnabled: false,
    authRequired: false
  });

  console.log('Testing message throughput...');
  
  const client = createSmtpClient({
    host: 'localhost',
    port: 2525,
    secure: false,
    connectionTimeout: 10000,
    socketTimeout: 10000
  });

  // Test with smaller message sizes to avoid timeout
  const sizes = [512, 1024]; // 512B, 1KB
  let totalBytes = 0;
  const startTime = Date.now();

  for (const size of sizes) {
    const content = 'x'.repeat(size);
    const email = new Email({
      from: 'sender@example.com',
      to: ['recipient@example.com'],
      subject: `Test ${size} bytes`,
      text: content,
    });

    const result = await client.sendMail(email);
    expect(result.success).toBeTrue();
    totalBytes += size;
  }
  
  const elapsed = Date.now() - startTime;
  const throughput = (totalBytes / elapsed) * 1000; // bytes per second
  
  console.log(`Total bytes sent: ${totalBytes}`);
  console.log(`Time elapsed: ${elapsed}ms`);
  console.log(`Throughput: ${(throughput / 1024).toFixed(1)} KB/s`);
  
  // Should achieve reasonable throughput (lowered expectation)
  expect(throughput).toBeGreaterThan(100); // At least 100 bytes/s
  
  await client.close();
  await stopTestServer(testServer);
});

tap.test('CPERF-05: network efficiency - batch sending', async () => {
  const testServer = await startTestServer({
    port: 2525,
    tlsEnabled: false,
    authRequired: false
  });

  console.log('Testing batch email sending...');

  const client = createSmtpClient({
    host: 'localhost',
    port: 2525,
    secure: false,
    connectionTimeout: 10000,
    socketTimeout: 10000
  });

  // Send 3 emails in batch
  const emails = Array(3).fill(null).map((_, i) => 
    new Email({
      from: 'sender@example.com',
      to: [`batch${i}@example.com`],
      subject: `Batch ${i}`,
      text: `Testing batch sending - message ${i}`,
    })
  );

  console.log('Sending 3 emails in batch...');
  const batchStart = Date.now();
  
  // Send emails sequentially
  for (let i = 0; i < emails.length; i++) {
    const result = await client.sendMail(emails[i]);
    expect(result.success).toBeTrue();
    console.log(`Email ${i + 1} sent`);
  }
  
  const batchTime = Date.now() - batchStart;
  
  console.log(`\nBatch complete: 3 emails in ${batchTime}ms`);
  console.log(`Average time per email: ${(batchTime / 3).toFixed(1)}ms`);
  
  // Batch should complete reasonably quickly
  expect(batchTime).toBeLessThan(5000); // Less than 5 seconds total
  
  await client.close();
  await stopTestServer(testServer);
});

tap.test('cleanup - stop SMTP server', async () => {
  // Cleanup is handled in individual tests
});

tap.start();
