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: 2562,
    tlsEnabled: false,
    authRequired: true
  });
  expect(testServer).toBeTruthy();
  expect(testServer.port).toBeGreaterThan(0);
});

tap.test('CSEC-02: OAuth2 authentication configuration', async () => {
  // Test client with OAuth2 configuration
  const smtpClient = createTestSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    auth: {
      oauth2: {
        user: 'oauth.user@example.com',
        clientId: 'client-id-12345',
        clientSecret: 'client-secret-67890',
        accessToken: 'access-token-abcdef',
        refreshToken: 'refresh-token-ghijkl'
      }
    },
    connectionTimeout: 5000,
    debug: true
  });

  // Test that OAuth2 config doesn't break the client
  try {
    const verified = await smtpClient.verify();
    console.log('Client with OAuth2 config created successfully');
    console.log('Note: Server does not support OAuth2, so auth will fail');
    expect(verified).toBeFalsy(); // Expected to fail without OAuth2 support
  } catch (error) {
    console.log('OAuth2 authentication attempt:', error.message);
  }

  await smtpClient.close();
});

tap.test('CSEC-02: OAuth2 vs regular auth', async () => {
  // Test regular auth (should work)
  const regularClient = createTestSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    auth: {
      user: 'testuser',
      pass: 'testpass'
    },
    connectionTimeout: 5000,
    debug: false
  });

  try {
    const verified = await regularClient.verify();
    console.log('Regular auth verification:', verified);
    
    if (verified) {
      // Send test email
      const email = new Email({
        from: 'sender@example.com',
        to: ['recipient@example.com'],
        subject: 'Test with regular auth',
        text: 'This uses regular PLAIN/LOGIN auth'
      });
      
      const result = await regularClient.sendMail(email);
      expect(result.success).toBeTruthy();
      console.log('Email sent with regular auth');
    }
  } catch (error) {
    console.log('Regular auth error:', error.message);
  }

  await regularClient.close();
});

tap.test('CSEC-02: OAuth2 error handling', async () => {
  // Test OAuth2 with invalid token
  const smtpClient = createTestSmtpClient({
    host: testServer.hostname,
    port: testServer.port,
    secure: false,
    auth: {
      method: 'OAUTH2',
      oauth2: {
        user: 'user@example.com',
        clientId: 'test-client',
        clientSecret: 'test-secret',
        refreshToken: 'refresh-token',
        accessToken: 'invalid-token'
      }
    },
    connectionTimeout: 5000,
    debug: false
  });

  try {
    const email = new Email({
      from: 'sender@example.com',
      to: ['recipient@example.com'],
      subject: 'OAuth2 test',
      text: 'Testing OAuth2 authentication'
    });
    
    const result = await smtpClient.sendMail(email);
    console.log('OAuth2 send result:', result.success);
  } catch (error) {
    console.log('OAuth2 error (expected):', error.message);
    expect(error.message).toInclude('auth');
  }

  await smtpClient.close();
});

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

tap.start();