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';
import * as dns from 'dns';
import { promisify } from 'util';

const resolveTxt = promisify(dns.resolveTxt);

let testServer: ITestServer;

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

tap.test('CSEC-05: DMARC record parsing', async () => {
  // Test DMARC record parsing
  const testDmarcRecords = [
    {
      domain: 'example.com',
      record: 'v=DMARC1; p=reject; rua=mailto:dmarc@example.com; ruf=mailto:forensics@example.com; adkim=s; aspf=s; pct=100',
      description: 'Strict DMARC with reporting'
    },
    {
      domain: 'relaxed.com',
      record: 'v=DMARC1; p=quarantine; adkim=r; aspf=r; pct=50',
      description: 'Relaxed alignment, 50% quarantine'
    },
    {
      domain: 'monitoring.com',
      record: 'v=DMARC1; p=none; rua=mailto:reports@monitoring.com',
      description: 'Monitor only mode'
    }
  ];

  console.log('DMARC Record Analysis:\n');
  
  for (const test of testDmarcRecords) {
    console.log(`Domain: _dmarc.${test.domain}`);
    console.log(`Record: ${test.record}`);
    console.log(`Description: ${test.description}`);
    
    // Parse DMARC tags
    const tags = test.record.match(/(\w+)=([^;]+)/g);
    if (tags) {
      console.log(`Tags found: ${tags.length}`);
    }
    console.log('');
  }
});

tap.test('CSEC-05: DMARC alignment testing', async () => {
  const smtpClient = createTestSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    connectionTimeout: 5000,
    debug: true
  });

  // Test DMARC alignment scenarios
  const alignmentTests = [
    {
      name: 'Fully aligned',
      fromHeader: 'sender@example.com',
      expectedResult: 'pass'
    },
    {
      name: 'Different domain',
      fromHeader: 'sender@otherdomain.com',
      expectedResult: 'fail'
    }
  ];

  for (const test of alignmentTests) {
    console.log(`\nTesting DMARC alignment: ${test.name}`);
    console.log(`  From header: ${test.fromHeader}`);
    
    const email = new Email({
      from: test.fromHeader,
      to: ['recipient@example.com'],
      subject: `DMARC Test: ${test.name}`,
      text: 'Testing DMARC alignment'
    });

    const result = await smtpClient.sendMail(email);
    expect(result.success).toBeTruthy();
    
    console.log(`  Email sent successfully`);
    console.log(`  Expected result: ${test.expectedResult}`);
  }

  await smtpClient.close();
});

tap.test('CSEC-05: DMARC policy enforcement', async () => {
  // Test different DMARC policies
  const policies = [
    {
      policy: 'none',
      description: 'Monitor only - no action taken',
      action: 'Deliver normally, send reports'
    },
    {
      policy: 'quarantine',
      description: 'Quarantine failing messages',
      action: 'Move to spam/junk folder'
    },
    {
      policy: 'reject',
      description: 'Reject failing messages',
      action: 'Bounce the message'
    }
  ];

  console.log('\nDMARC Policy Actions:\n');
  
  for (const p of policies) {
    console.log(`Policy: p=${p.policy}`);
    console.log(`  Description: ${p.description}`);
    console.log(`  Action: ${p.action}`);
    console.log('');
  }
});

tap.test('CSEC-05: DMARC deployment best practices', async () => {
  // DMARC deployment phases
  const deploymentPhases = [
    {
      phase: 1,
      policy: 'p=none; rua=mailto:dmarc@example.com',
      description: 'Monitor only - collect data'
    },
    {
      phase: 2,
      policy: 'p=quarantine; pct=10; rua=mailto:dmarc@example.com',
      description: 'Quarantine 10% of failing messages'
    },
    {
      phase: 3,
      policy: 'p=reject; rua=mailto:dmarc@example.com',
      description: 'Reject all failing messages'
    }
  ];

  console.log('\nDMARC Deployment Best Practices:\n');
  
  for (const phase of deploymentPhases) {
    console.log(`Phase ${phase.phase}: ${phase.description}`);
    console.log(`  Record: v=DMARC1; ${phase.policy}`);
    console.log('');
  }
});

tap.test('CSEC-05: DMARC record lookup', async () => {
  // Test real DMARC record lookups
  const testDomains = ['paypal.com'];
  
  console.log('\nReal DMARC Record Lookups:\n');
  
  for (const domain of testDomains) {
    const dmarcDomain = `_dmarc.${domain}`;
    console.log(`Domain: ${domain}`);
    
    try {
      const txtRecords = await resolveTxt(dmarcDomain);
      const dmarcRecords = txtRecords
        .map(record => record.join(''))
        .filter(record => record.startsWith('v=DMARC1'));
      
      if (dmarcRecords.length > 0) {
        const record = dmarcRecords[0];
        console.log(`  Record found: ${record.substring(0, 50)}...`);
        
        // Parse key elements
        const policyMatch = record.match(/p=(\w+)/);
        if (policyMatch) console.log(`  Policy: ${policyMatch[1]}`);
      } else {
        console.log('  No DMARC record found');
      }
    } catch (error) {
      console.log(`  Lookup failed: ${error.message}`);
    }
    console.log('');
  }
});

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

tap.start();