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

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).toBeGreaterThan(0);
});

tap.test('CSEC-10: Reputation-based filtering', async () => {
  const smtpClient = createTestSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false
  });

  const email = new Email({
    from: 'sender@example.com',
    to: ['recipient@example.com'],
    subject: 'Reputation test',
    text: 'Testing reputation-based filtering'
  });

  const result = await smtpClient.sendMail(email);
  console.log('Good reputation: Message accepted');
  expect(result.success).toBeTruthy();

  await smtpClient.close();
});

tap.test('CSEC-10: Content filtering and spam scoring', async () => {
  const smtpClient = createTestSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false
  });

  // Test 1: Clean email
  const cleanEmail = new Email({
    from: 'sender@example.com',
    to: ['recipient@example.com'],
    subject: 'Business proposal',
    text: 'I would like to discuss our upcoming project. Please let me know your availability.'
  });

  const cleanResult = await smtpClient.sendMail(cleanEmail);
  console.log('Clean email: Accepted');
  expect(cleanResult.success).toBeTruthy();

  // Test 2: Email with spam-like content
  const spamEmail = new Email({
    from: 'sender@example.com',
    to: ['recipient@example.com'],
    subject: 'You are a WINNER!',
    text: 'Click here to claim your lottery prize! Act now! 100% guarantee!'
  });

  const spamResult = await smtpClient.sendMail(spamEmail);
  console.log('Spam-like email: Processed by server');
  expect(spamResult.success).toBeTruthy();

  await smtpClient.close();
});

tap.test('CSEC-10: Greylisting simulation', async () => {
  const smtpClient = createTestSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false
  });

  const email = new Email({
    from: 'sender@example.com',
    to: ['recipient@example.com'],
    subject: 'Greylist test',
    text: 'Testing greylisting mechanism'
  });

  // Test server doesn't implement greylisting, so this should succeed
  const result = await smtpClient.sendMail(email);
  console.log('Email sent (greylisting not active on test server)');
  expect(result.success).toBeTruthy();

  await smtpClient.close();
});

tap.test('CSEC-10: DNS blacklist checking', async () => {
  const smtpClient = createTestSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false
  });

  // Test with various domains
  const testDomains = [
    { from: 'sender@clean-domain.com', expected: true },
    { from: 'sender@spam-domain.com', expected: true } // Test server accepts all
  ];

  for (const test of testDomains) {
    const email = new Email({
      from: test.from,
      to: ['recipient@example.com'],
      subject: 'DNSBL test',
      text: 'Testing DNSBL checking'
    });

    const result = await smtpClient.sendMail(email);
    console.log(`Sender ${test.from}: ${result.success ? 'accepted' : 'rejected'}`);
    expect(result.success).toBeTruthy();
  }

  await smtpClient.close();
});

tap.test('CSEC-10: Connection behavior analysis', async () => {
  // Test normal behavior
  const smtpClient = createTestSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false
  });

  const email = new Email({
    from: 'sender@example.com',
    to: ['recipient@example.com'],
    subject: 'Behavior test',
    text: 'Testing normal email sending behavior'
  });

  const result = await smtpClient.sendMail(email);
  console.log('Normal behavior: Accepted');
  expect(result.success).toBeTruthy();

  await smtpClient.close();
});

tap.test('CSEC-10: Attachment scanning', async () => {
  const smtpClient = createTestSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false
  });

  // Test 1: Safe attachment
  const safeEmail = new Email({
    from: 'sender@example.com',
    to: ['recipient@example.com'],
    subject: 'Document for review',
    text: 'Please find the attached document.',
    attachments: [{
      filename: 'report.pdf',
      content: Buffer.from('PDF content here'),
      contentType: 'application/pdf'
    }]
  });

  const safeResult = await smtpClient.sendMail(safeEmail);
  console.log('Safe attachment: Accepted');
  expect(safeResult.success).toBeTruthy();

  // Test 2: Potentially dangerous attachment (test server accepts all)
  const exeEmail = new Email({
    from: 'sender@example.com',
    to: ['recipient@example.com'],
    subject: 'Important update',
    text: 'Please run the attached file',
    attachments: [{
      filename: 'update.exe',
      content: Buffer.from('MZ\x90\x00\x03'),  // Fake executable header
      contentType: 'application/octet-stream'
    }]
  });

  const exeResult = await smtpClient.sendMail(exeEmail);
  console.log('Executable attachment: Processed by server');
  expect(exeResult.success).toBeTruthy();

  await smtpClient.close();
});

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

tap.start();