using System.Text.Json;
using Health.Application.Medications;
using Health.Application.Notifications;
using Microsoft.Extensions.Logging;

namespace Health.Infrastructure.Medications;

public sealed class OutboxMedicationReminderDispatcher(
    IUserNotificationProducer notifications,
    ILogger<OutboxMedicationReminderDispatcher> logger) : IMedicationReminderDispatcher
{
    private readonly IUserNotificationProducer _notifications = notifications;
    private readonly ILogger<OutboxMedicationReminderDispatcher> _logger = logger;

    public async Task DispatchAsync(MedicationReminderTask task, CancellationToken ct)
    {
        var details = string.Join(" · ", new[]
        {
            task.Dosage,
            task.ScheduledTime.ToString("HH:mm")
        }.Where(x => !string.IsNullOrWhiteSpace(x)));
        await _notifications.EnqueueAsync(
            task.UserId,
            task.TaskId,
            new NotificationMessage(
                "MedicationReminder",
                "用药时间到了",
                $"请按计划服用{task.Name}{(details.Length > 0 ? $"（{details}）" : "")}，服用后记得打卡。",
                "info",
                "medication",
                task.MedicationId.ToString()),
            ct);

        _logger.LogInformation(
            "用药提醒已写入通知 Outbox，等待推送服务: {TaskId} {UserId}",
            task.TaskId,
            task.UserId);
    }
}
