import assert from 'node:assert/strict';
import test from 'node:test';
import {
  extractTemplateVariables,
  renderNotificationTemplate,
  renderTemplateString,
} from './template-renderer';

test('extractTemplateVariables deduplicates placeholders across template', () => {
  assert.deepEqual(extractTemplateVariables('Hello {{name}} {{name}} {{customer.code}}'), [
    'name',
    'customer.code',
  ]);
});

test('renderTemplateString replaces nested tokens and defaults missing values', () => {
  assert.equal(
    renderTemplateString('Quotation {{quotation.code}} for {{customerName}}', {
      quotation: { code: 'QT-001' },
      customerName: 'ACME',
    }),
    'Quotation QT-001 for ACME',
  );

  assert.equal(
    renderTemplateString('Missing {{unknown}}', {}),
    'Missing -',
  );
});

test('renderNotificationTemplate generates html and plain text bodies', () => {
  const rendered = renderNotificationTemplate(
    {
      subjectTemplate: 'Approved {{quotationCode}}',
      titleTemplate: 'Approved {{quotationCode}}',
      bodyTemplate: '<p>Hello {{customerName}}</p><br/>Ready</p>',
      bodyFormat: 'html',
      linkTemplate: '/q/{{quotationId}}',
    },
    {
      quotationCode: 'QT-2026-001',
      quotationId: 'quo-1',
      customerName: 'ACME',
    },
  );

  assert.equal(rendered.subject, 'Approved QT-2026-001');
  assert.equal(rendered.bodyHtml, '<p>Hello ACME</p><br/>Ready</p>');
  assert.match(rendered.bodyText, /Hello ACME/);
  assert.equal(rendered.linkUrl, '/q/quo-1');
  assert.deepEqual(rendered.variables.sort(), [
    'customerName',
    'quotationCode',
    'quotationId',
  ]);
});
