import assert from 'node:assert/strict';
import { test } from 'node:test';

import { decodeMimeHeader, parseInboundMessage } from '../src/inbound-mail.js';

test('parseInboundMessage extracts common headers and text bodies from MIME', async () => {
  const rawMessage = [
    'From: Alice <alice@example.net>',
    'To: Support <support@inbound.example>',
    'Subject: =?UTF-8?B?5pS25L+h5rWL6K+V?=',
    'Message-ID: <mime-test@example.net>',
    'MIME-Version: 1.0',
    'Content-Type: multipart/alternative; boundary="alt"',
    '',
    '--alt',
    'Content-Type: text/plain; charset=UTF-8',
    'Content-Transfer-Encoding: base64',
    '',
    Buffer.from('Hello plain body.', 'utf8').toString('base64'),
    '--alt',
    'Content-Type: text/html; charset=UTF-8',
    'Content-Transfer-Encoding: quoted-printable',
    '',
    '<p>Hello <strong>HTML</strong> body.</p>',
    '--alt--',
    ''
  ].join('\r\n');

  const parsed = await parseInboundMessage(rawMessage, ['support@inbound.example']);

  assert.equal(parsed.sender, 'alice@example.net');
  assert.deepEqual(parsed.recipients, ['support@inbound.example']);
  assert.equal(parsed.subject, '收信测试');
  assert.equal(parsed.messageId, '<mime-test@example.net>');
  assert.equal(parsed.textBody, 'Hello plain body.');
  assert.match(parsed.htmlBody, /<strong>HTML<\/strong>/);
  assert.equal(parsed.preview, 'Hello plain body.');
});

test('decodeMimeHeader joins folded UTF-8 encoded words without introducing spaces', () => {
  const encoded = [
    '=?UTF-8?Q?=E6=A0=B8=E4=BA=91?=',
    ' =?UTF-8?Q?=E8=AE=A1=E7=AE=97=E5=B9=B3=E5=8F=B0?=',
    ' =?UTF-8?Q?_MailHub_=E6=B5=8B=E8=AF=95?='
  ].join('\r\n');

  assert.equal(decodeMimeHeader(encoded), '核云计算平台 MailHub 测试');
});

test('decodeMimeHeader preserves plain text and malformed encoded words', () => {
  assert.equal(decodeMimeHeader('literal?= =?UTF-8?Q?B?='), 'literal?= B');
  assert.equal(decodeMimeHeader('=?UTF-8?B?!!!!?='), '=?UTF-8?B?!!!!?=');
  assert.equal(decodeMimeHeader('=?UTF-8?B?/w==?='), '=?UTF-8?B?/w==?=');
});

test('parseInboundMessage does not expose attachment-only multipart wire data as text', async () => {
  const rawMessage = [
    'From: Alice <alice@example.net>',
    'To: Support <support@inbound.example>',
    'Subject: Attachment only',
    'MIME-Version: 1.0',
    'Content-Type: multipart/mixed; boundary="mixed"',
    '',
    '--mixed',
    'Content-Type: application/pdf; name="report.pdf"',
    'Content-Disposition: attachment; filename="report.pdf"',
    'Content-Transfer-Encoding: base64',
    '',
    'JVBERi0xLjQ=',
    '--mixed--',
    ''
  ].join('\r\n');

  const parsed = await parseInboundMessage(rawMessage, ['support@inbound.example']);

  assert.equal(parsed.textBody, '');
  assert.equal(parsed.htmlBody, '');
  assert.equal(parsed.preview, '');
});
