'use strict';

// BM3 — the reminder notifier used a hard-coded 3-day early reminder and never
// read the bill's reminder_days_before, so the "Reminder days before" control
// was a no-op. These tests pin the now-honored per-bill lead time (pure logic,
// no clock/senders) and the dynamic email wording.
const test = require('node:test');
const assert = require('node:assert/strict');

const { _reminders, _email } = require('../services/notificationService');
const { reminderTypeFor, leadDaysOf, TYPE_META } = _reminders;

test('leadDaysOf defaults to 3 and honors an integer reminder_days_before', () => {
  assert.equal(leadDaysOf({}), 3);
  assert.equal(leadDaysOf({ reminder_days_before: null }), 3);
  assert.equal(leadDaysOf({ reminder_days_before: 7 }), 7);
  assert.equal(leadDaysOf({ reminder_days_before: 0 }), 0);
});

test('a 7-day lead fires the early reminder at 7 days out, NOT at 3', () => {
  const bill = { reminder_days_before: 7 };
  assert.equal(reminderTypeFor(bill, 7), 'due_3d', 'early reminder at the chosen lead');
  assert.equal(reminderTypeFor(bill, 3), null, 'no reminder at the old fixed 3 days');
});

test('default (no reminder_days_before) still fires at 3 days — backwards compatible', () => {
  assert.equal(reminderTypeFor({}, 3), 'due_3d');
  assert.equal(reminderTypeFor({}, 5), null);
});

test('1-day and same-day reminders are unaffected and never double up with a small lead', () => {
  // lead of 1 → the early reminder is suppressed (due_1d covers it)
  assert.equal(reminderTypeFor({ reminder_days_before: 1 }, 1), 'due_1d');
  // lead of 0 → due_today covers it
  assert.equal(reminderTypeFor({ reminder_days_before: 0 }, 0), 'due_today');
  // generic day/overdue selection
  assert.equal(reminderTypeFor({ reminder_days_before: 5 }, 1), 'due_1d');
  assert.equal(reminderTypeFor({ reminder_days_before: 5 }, 0), 'due_today');
  assert.equal(reminderTypeFor({ reminder_days_before: 5 }, -2), 'overdue');
  assert.equal(reminderTypeFor({ reminder_days_before: 5 }, 4), null);
});

test('email subject + body reflect the actual lead days', () => {
  const bill = { name: 'Insurance', expected_amount: 12000, reminder_days_before: 7 };
  assert.match(TYPE_META.due_3d.subject(bill), /due in 7 days/);
  const html = _email.buildEmailHtml(bill, 'due_3d', '2026-07-10');
  assert.match(html, /is due in 7 days/);
});
