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 queue management tests', async () => {
  // Just a placeholder to ensure server starts properly
});

tap.test('CPERF-07: queue management - basic queue processing', async () => {
  const testServer = await startTestServer({
    port: 2525,
    tlsEnabled: false,
    authRequired: false
  });

  console.log('Testing basic queue processing...');
  
  const client = createSmtpClient({
    host: 'localhost',
    port: 2525,
    secure: false
  });

  // Queue up 5 emails (reduced from 10)
  const emailCount = 5;
  const emails = Array(emailCount).fill(null).map((_, i) => 
    new Email({
      from: 'sender@example.com',
      to: [`queue${i}@example.com`],
      subject: `Queue test ${i}`,
      text: `Testing queue management - message ${i}`,
    })
  );

  console.log(`Sending ${emailCount} emails...`);
  const queueStart = Date.now();
  
  // Send all emails sequentially
  const results = [];
  for (let i = 0; i < emails.length; i++) {
    const result = await client.sendMail(emails[i]);
    console.log(`  Email ${i} sent`);
    results.push(result);
  }
  
  const queueTime = Date.now() - queueStart;
  
  // Verify all succeeded
  results.forEach((result, index) => {
    expect(result.success).toBeTrue();
  });
  
  console.log(`All ${emailCount} emails processed in ${queueTime}ms`);
  console.log(`Average time per email: ${(queueTime / emailCount).toFixed(1)}ms`);
  
  // Should complete within reasonable time
  expect(queueTime).toBeLessThan(10000); // Less than 10 seconds for 5 emails
  
  await client.close();
  await stopTestServer(testServer);
});

tap.test('CPERF-07: queue management - queue with rate limiting', async () => {
  const testServer = await startTestServer({
    port: 2526,
    tlsEnabled: false,
    authRequired: false
  });

  console.log('Testing queue with rate limiting...');
  
  const client = createSmtpClient({
    host: 'localhost',
    port: 2526,
    secure: false
  });

  // Send 5 emails sequentially (simulating rate limiting)
  const emailCount = 5;
  const rateLimitDelay = 200; // 200ms between emails
  
  console.log(`Sending ${emailCount} emails with ${rateLimitDelay}ms rate limit...`);
  const rateStart = Date.now();
  
  for (let i = 0; i < emailCount; i++) {
    const email = new Email({
      from: 'sender@example.com',
      to: [`ratelimit${i}@example.com`],
      subject: `Rate limit test ${i}`,
      text: `Testing rate limited queue - message ${i}`,
    });
    
    const result = await client.sendMail(email);
    expect(result.success).toBeTrue();
    
    console.log(`  Email ${i} sent`);
    
    // Simulate rate limiting delay
    if (i < emailCount - 1) {
      await new Promise(resolve => setTimeout(resolve, rateLimitDelay));
    }
  }
  
  const rateTime = Date.now() - rateStart;
  const expectedMinTime = (emailCount - 1) * rateLimitDelay;
  
  console.log(`Rate limited emails sent in ${rateTime}ms`);
  console.log(`Expected minimum time: ${expectedMinTime}ms`);
  
  // Should respect rate limiting
  expect(rateTime).toBeGreaterThanOrEqual(expectedMinTime);
  
  await client.close();
  await stopTestServer(testServer);
});

tap.test('CPERF-07: queue management - sequential processing', async () => {
  const testServer = await startTestServer({
    port: 2527,
    tlsEnabled: false,
    authRequired: false
  });

  console.log('Testing sequential email processing...');
  
  const client = createSmtpClient({
    host: 'localhost',
    port: 2527,
    secure: false
  });

  // Send multiple emails sequentially
  const emails = Array(3).fill(null).map((_, i) => 
    new Email({
      from: 'sender@example.com',
      to: [`sequential${i}@example.com`],
      subject: `Sequential test ${i}`,
      text: `Testing sequential processing - message ${i}`,
    })
  );

  console.log('Sending 3 emails sequentially...');
  const sequentialStart = Date.now();
  
  const results = [];
  for (const email of emails) {
    const result = await client.sendMail(email);
    results.push(result);
  }
  
  const sequentialTime = Date.now() - sequentialStart;
  
  // All should succeed
  results.forEach((result, index) => {
    expect(result.success).toBeTrue();
    console.log(`  Email ${index} processed`);
  });
  
  console.log(`Sequential processing completed in ${sequentialTime}ms`);
  console.log(`Average time per email: ${(sequentialTime / 3).toFixed(1)}ms`);
  
  await client.close();
  await stopTestServer(testServer);
});

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

tap.start();
