using System.Text.Json;
using Microsoft.Extensions.Logging;
using Quartz;
using UniVerse.Application.DTOs.Notifications;
using UniVerse.Application.Interfaces;

namespace UniVerse.Infrastructure.Notifications;

[DisallowConcurrentExecution]
public class NotificationJob : IJob
{
    public const string MessageDataKey = "message";

    private readonly INotificationService _notifications;
    private readonly ILogger<NotificationJob> _logger;

    public NotificationJob(INotificationService notifications, ILogger<NotificationJob> logger)
    {
        _notifications = notifications;
        _logger = logger;
    }

    public async Task Execute(IJobExecutionContext context)
    {
        var payload = context.MergedJobDataMap.GetString(MessageDataKey);
        if (string.IsNullOrWhiteSpace(payload))
        {
            _logger.LogWarning("Notification job {JobKey} does not contain message payload", context.JobDetail.Key);
            return;
        }

        var message = JsonSerializer.Deserialize<NotificationMessage>(payload)
            ?? throw new InvalidOperationException("Scheduled notification payload cannot be deserialized.");

        await _notifications.SendAsync(message, context.CancellationToken);
    }
}
