using SolutionErp.Application.Common.Interfaces;
using SolutionErp.Application.Notifications;
using SolutionErp.Domain.Notifications;

namespace SolutionErp.Infrastructure.Services;

// MVP: writes directly to DbContext. Does NOT call SaveChanges — caller's unit of
// work flushes both the domain mutation and the notification atomically.
// Future: wrap with SignalR IHubContext push + Outbox for email dispatch.
public class NotificationService(IApplicationDbContext db, IDateTime clock) : INotificationService
{
    public Task NotifyAsync(
        Guid userId,
        NotificationType type,
        string title,
        string? description = null,
        string? href = null,
        Guid? refId = null,
        CancellationToken ct = default)
    {
        db.Notifications.Add(new Notification
        {
            UserId = userId,
            Type = type,
            Title = title,
            Description = description,
            Href = href,
            RefId = refId,
            CreatedAt = clock.UtcNow,
        });
        return Task.CompletedTask;
    }

    public Task NotifyManyAsync(
        IEnumerable<Guid> userIds,
        NotificationType type,
        string title,
        string? description = null,
        string? href = null,
        Guid? refId = null,
        CancellationToken ct = default)
    {
        var now = clock.UtcNow;
        foreach (var userId in userIds.Distinct())
        {
            db.Notifications.Add(new Notification
            {
                UserId = userId,
                Type = type,
                Title = title,
                Description = description,
                Href = href,
                RefId = refId,
                CreatedAt = now,
            });
        }
        return Task.CompletedTask;
    }
}
