const test = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const path = require('node:path');
const { makeRawEmail } = require('./gw.js');

test('help documents attachment support for send', () => {
  const gwPath = path.join(__dirname, 'gw.js');
  const result = spawnSync(process.execPath, [gwPath, 'help'], { encoding: 'utf8' });

  assert.equal(result.status, 0, result.stderr);
  assert.match(result.stdout, /send --to <email> --subject <text> --body <text> \[--html\] \[--attach <file>\]/);
});

test('makeRawEmail builds multipart messages when attachments are present', () => {
  const raw = makeRawEmail({
    from: 'stefano@fiorinis.com',
    to: 'stefano@fiorinis.com',
    subject: 'Attachment test',
    body: 'Attached PDF.',
    attachments: [
      {
        filename: 'report.pdf',
        contentType: 'application/pdf',
        data: Buffer.from('%PDF-1.4\n%test\n').toString('base64'),
      },
    ],
  });

  const decoded = Buffer.from(raw, 'base64').toString('utf8');
  assert.match(decoded, /Content-Type: multipart\/mixed; boundary=/);
  assert.match(decoded, /Content-Disposition: attachment; filename="report\.pdf"/);
  assert.match(decoded, /Content-Type: application\/pdf; name="report\.pdf"/);
});
