#nullable enable
using Baya.Application.Contracts.Common;
using NotificationMessage = Baya.Application.Contracts.Common.Notification;
using NotificationEntity = Baya.Domain.Entities.Notifications.Notification;

namespace Baya.Infrastructure.Persistence.Services.Notifications;

/// <summary>
/// Real in-app implementation of <see cref="INotificationDispatcher"/> — supersedes the b0 log/no-op
/// stub. It writes a <c>notifications</c> row for the in-app channel. SMS/push are deferred behind this
/// same seam; those channels are no-ops for now so callers use <see cref="DispatchAsync"/> unchanged.
/// </summary>
internal sealed class InAppNotificationDispatcher(ApplicationDbContext db, IDateTimeProvider dateTimeProvider) : INotificationDispatcher
{
    public async ValueTask DispatchAsync(NotificationMessage notification, CancellationToken cancellationToken = default)
    {
        if (notification.Channel != NotificationChannel.InApp)
            return;

        db.Set<NotificationEntity>().Add(new NotificationEntity
        {
            UserId = notification.RecipientUserId,
            Type = notification.Type,
            Title = notification.Title,
            Body = notification.Body,
            DataJson = notification.DataJson,
            IsRead = false,
            CreatedAt = dateTimeProvider.UtcNow
        });

        await db.SaveChangesAsync(cancellationToken);
    }
}
