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

let testServer: ITestServer;

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

tap.test('CEP-09: Basic priority headers', async () => {
  const smtpClient = await createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000
  });

  // Test different priority levels
  const priorityLevels = [
    { priority: 'high', headers: { 'X-Priority': '1', 'Importance': 'high' } },
    { priority: 'normal', headers: { 'X-Priority': '3', 'Importance': 'normal' } },
    { priority: 'low', headers: { 'X-Priority': '5', 'Importance': 'low' } }
  ];

  for (const level of priorityLevels) {
    console.log(`Testing ${level.priority} priority email...`);
    
    const email = new Email({
      from: 'sender@example.com',
      to: 'recipient@example.com',
      subject: `${level.priority.toUpperCase()} Priority Test`,
      text: `This is a ${level.priority} priority message`,
      priority: level.priority as 'high' | 'normal' | 'low'
    });

    const result = await smtpClient.sendMail(email);
    expect(result.success).toBeTruthy();
  }
  
  console.log('Basic priority headers test completed successfully');
});

tap.test('CEP-09: Multiple priority header formats', async () => {
  const smtpClient = await createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000
  });

  // Test various priority header combinations
  const email = new Email({
    from: 'sender@example.com',
    to: 'recipient@example.com',
    subject: 'Multiple Priority Headers Test',
    text: 'Testing various priority header formats',
    headers: {
      'X-Priority': '1 (Highest)',
      'X-MSMail-Priority': 'High',
      'Importance': 'high',
      'Priority': 'urgent',
      'X-Message-Flag': 'Follow up'
    }
  });

  const result = await smtpClient.sendMail(email);
  expect(result.success).toBeTruthy();
  console.log('Multiple priority header formats test sent successfully');
});

tap.test('CEP-09: Client-specific priority mappings', async () => {
  const smtpClient = await createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000
  });

  // Send test email with comprehensive priority headers
  const email = new Email({
    from: 'sender@example.com',
    to: 'recipient@example.com',
    subject: 'Cross-client Priority Test',
    text: 'This should appear as high priority in all clients',
    priority: 'high'
  });

  const result = await smtpClient.sendMail(email);
  expect(result.success).toBeTruthy();
  console.log('Client-specific priority mappings test sent successfully');
});

tap.test('CEP-09: Sensitivity and confidentiality headers', async () => {
  const smtpClient = await createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000
  });

  // Test sensitivity levels
  const sensitivityLevels = [
    { level: 'Personal', description: 'Personal information' },
    { level: 'Private', description: 'Private communication' },
    { level: 'Company-Confidential', description: 'Internal use only' },
    { level: 'Normal', description: 'No special handling' }
  ];

  for (const sensitivity of sensitivityLevels) {
    const email = new Email({
      from: 'sender@example.com',
      to: 'recipient@example.com',
      subject: `${sensitivity.level} Message`,
      text: sensitivity.description,
      headers: {
        'Sensitivity': sensitivity.level,
        'X-Sensitivity': sensitivity.level
      }
    });

    const result = await smtpClient.sendMail(email);
    expect(result.success).toBeTruthy();
  }
  
  console.log('Sensitivity and confidentiality headers test completed successfully');
});

tap.test('CEP-09: Auto-response suppression headers', async () => {
  const smtpClient = await createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000
  });

  // Headers to suppress auto-responses (vacation messages, etc.)
  const email = new Email({
    from: 'noreply@example.com',
    to: 'recipient@example.com',
    subject: 'Automated Notification',
    text: 'This is an automated message. Please do not reply.',
    headers: {
      'X-Auto-Response-Suppress': 'All', // Microsoft
      'Auto-Submitted': 'auto-generated', // RFC 3834
      'Precedence': 'bulk', // Traditional
      'X-Autoreply': 'no',
      'X-Autorespond': 'no',
      'List-Id': '<notifications.example.com>', // Mailing list header
      'List-Unsubscribe': '<mailto:unsubscribe@example.com>'
    }
  });

  const result = await smtpClient.sendMail(email);
  expect(result.success).toBeTruthy();
  console.log('Auto-response suppression headers test sent successfully');
});

tap.test('CEP-09: Expiration and retention headers', async () => {
  const smtpClient = await createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000
  });

  // Set expiration date for the email
  const expirationDate = new Date();
  expirationDate.setDate(expirationDate.getDate() + 7); // Expires in 7 days

  const email = new Email({
    from: 'sender@example.com',
    to: 'recipient@example.com',
    subject: 'Time-sensitive Information',
    text: 'This information expires in 7 days',
    headers: {
      'Expiry-Date': expirationDate.toUTCString(),
      'X-Message-TTL': '604800', // 7 days in seconds
      'X-Auto-Delete-After': expirationDate.toISOString(),
      'X-Retention-Date': expirationDate.toISOString()
    }
  });

  const result = await smtpClient.sendMail(email);
  expect(result.success).toBeTruthy();
  console.log('Expiration and retention headers test sent successfully');
});

tap.test('CEP-09: Message flags and categories', async () => {
  const smtpClient = await createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000
  });

  // Test various message flags and categories
  const flaggedEmails = [
    {
      flag: 'Follow up',
      category: 'Action Required',
      color: 'red'
    },
    {
      flag: 'For Your Information',
      category: 'Informational',
      color: 'blue'
    },
    {
      flag: 'Review',
      category: 'Pending Review',
      color: 'yellow'
    }
  ];

  for (const flaggedEmail of flaggedEmails) {
    const email = new Email({
      from: 'sender@example.com',
      to: 'recipient@example.com',
      subject: `${flaggedEmail.flag}: Important Document`,
      text: `This email is flagged as: ${flaggedEmail.flag}`,
      headers: {
        'X-Message-Flag': flaggedEmail.flag,
        'X-Category': flaggedEmail.category,
        'X-Color-Label': flaggedEmail.color,
        'Keywords': flaggedEmail.flag.replace(' ', '-')
      }
    });

    const result = await smtpClient.sendMail(email);
    expect(result.success).toBeTruthy();
  }
  
  console.log('Message flags and categories test completed successfully');
});

tap.test('CEP-09: Priority with delivery timing', async () => {
  const smtpClient = await createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000
  });

  // Test deferred delivery with priority
  const futureDate = new Date();
  futureDate.setHours(futureDate.getHours() + 2); // Deliver in 2 hours

  const email = new Email({
    from: 'sender@example.com',
    to: 'recipient@example.com',
    subject: 'Scheduled High Priority Message',
    text: 'This high priority message should be delivered at a specific time',
    priority: 'high',
    headers: {
      'Deferred-Delivery': futureDate.toUTCString(),
      'X-Delay-Until': futureDate.toISOString(),
      'X-Priority': '1',
      'Importance': 'High'
    }
  });

  const result = await smtpClient.sendMail(email);
  expect(result.success).toBeTruthy();
  console.log('Priority with delivery timing test sent successfully');
});

tap.test('CEP-09: Priority impact on routing', async () => {
  const smtpClient = await createSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000
  });

  // Test batch of emails with different priorities
  const emails = [
    { priority: 'high', subject: 'URGENT: Server Down' },
    { priority: 'high', subject: 'Critical Security Update' },
    { priority: 'normal', subject: 'Weekly Report' },
    { priority: 'low', subject: 'Newsletter' },
    { priority: 'low', subject: 'Promotional Offer' }
  ];

  for (const emailData of emails) {
    const email = new Email({
      from: 'sender@example.com',
      to: 'recipient@example.com',
      subject: emailData.subject,
      text: `Priority: ${emailData.priority}`,
      priority: emailData.priority as 'high' | 'normal' | 'low'
    });

    const result = await smtpClient.sendMail(email);
    expect(result.success).toBeTruthy();
  }
  
  console.log('Priority impact on routing test completed successfully');
});

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

export default tap.start();