import assert from 'node:assert/strict';
import test from 'node:test';
import { startScheduleReminderWorker } from './schedule-reminder-worker.mjs';

test('schedule reminder worker sends due daily todo digest', async () => {
  const calls = [];
  const sent = [];
  const subscription = {
    id: 'sub-1',
    userId: 'user-1',
    hour: 7,
    minute: 0,
    timezone: 'Asia/Shanghai',
    channel: 'wechat',
    attempts: 1,
  };
  const worker = startScheduleReminderWorker({
    intervalMs: 60_000,
    scheduleService: {
      async listDueDigestSubscriptions() {
        calls.push('list');
        return [subscription];
      },
      async lockDigestSubscription(id) {
        calls.push(`lock:${id}`);
        return subscription;
      },
      async buildTodoDigestText({ userId }) {
        calls.push(`digest:${userId}`);
        return '6月18日 待办记录\n\n1. 开会';
      },
      async logDelivery(input) {
        calls.push(`log:${input.status}`);
      },
      async markDigestSent(input) {
        calls.push(`sent:${input.id}`);
      },
      async markDigestFailed() {
        calls.push('failed');
      },
    },
    async sendWechatTextToUser(userId, text) {
      sent.push({ userId, text });
    },
    logger: { warn() {} },
    runOnStart: false,
  });

  await worker.runOnce();
  worker.stop();

  assert.deepEqual(sent, [{ userId: 'user-1', text: '6月18日 待办记录\n\n1. 开会' }]);
  assert.deepEqual(calls, ['list', 'lock:sub-1', 'digest:user-1', 'log:success', 'sent:sub-1']);
});
