using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Tiku.Application.Notifications;
using Tiku.Domain.Common;
using Tiku.Domain.Operations;
using Tiku.Infrastructure.Persistence;

namespace Tiku.Infrastructure.Notifications;

internal sealed class InAppNotificationProvider(TikuDbContext dbContext) : INotificationProvider
{
    public async Task<UserNotification> UpsertInAppAsync(
        InAppNotificationRequest request,
        CancellationToken cancellationToken = default)
    {
        var item = !string.IsNullOrWhiteSpace(request.DedupeKey)
            ? await dbContext.UserNotifications.FirstOrDefaultAsync(notification =>
                    notification.TenantId == request.TenantId &&
                    notification.UserId == request.UserId &&
                    notification.NotificationType == request.NotificationType &&
                    notification.DedupeKey == request.DedupeKey,
                cancellationToken)
            : null;

        var isNew = item is null;
        item ??= new UserNotification
        {
            TenantId = request.TenantId,
            UserId = request.UserId,
            CreatedBy = request.CreatedBy
        };

        item.NotificationType = request.NotificationType.Trim();
        item.Severity = request.Severity;
        item.Title = request.Title.Trim();
        item.Message = request.Message.Trim();
        item.ActionLabel = Normalize(request.ActionLabel);
        item.ActionPath = Normalize(request.ActionPath);
        item.SourceType = Normalize(request.SourceType);
        item.SourceId = request.SourceId;
        item.DedupeKey = Normalize(request.DedupeKey);
        item.Metadata = request.Metadata.ValueKind == JsonValueKind.Object
            ? request.Metadata.Clone()
            : JsonDefaults.Object();

        if (isNew) dbContext.UserNotifications.Add(item);

        return item;
    }

    private static string? Normalize(string? value)
    {
        return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
    }
}