using System.Text.Json;
using Health.Application.Exercises;
using Health.Application.Notifications;

namespace Health.Infrastructure.Exercises;

public sealed class ExerciseReminderProducer(AppDbContext db, IUserNotificationProducer notifications) : IExerciseReminderProducer
{
    private readonly AppDbContext _db = db;
    private readonly IUserNotificationProducer _notifications = notifications;

    public async Task<int> ProduceDueAsync(DateTime utcNow, CancellationToken ct)
    {
        var beijingNow = utcNow.AddHours(8);
        var today = DateOnly.FromDateTime(beijingNow);
        var currentTime = TimeOnly.FromDateTime(beijingNow);
        var dueItems = await _db.ExercisePlanItems.AsNoTracking()
            .Include(x => x.Plan)
            .Where(x => x.ScheduledDate == today && !x.IsCompleted && !x.IsRestDay && x.Plan.ReminderTime <= currentTime)
            .ToListAsync(ct);
        var created = 0;
        foreach (var item in dueItems)
        {
            if (await _notifications.EnqueueAsync(
                item.Plan.UserId,
                item.Id,
                new NotificationMessage(
                    "ExerciseReminder",
                    "今日运动计划",
                    $"今天安排了 {item.ExerciseType} {item.DurationMinutes} 分钟，完成后记得打卡。",
                    "info",
                    "exercise",
                    item.PlanId.ToString()),
                ct))
                created++;
        }
        return created;
    }
}
