using Knot.Shared.Kernel;
using Knot.Shared.Kernel.Events;
using Knot.Modules.Relations.Application.Abstractions;
using Knot.Modules.Relations.Domain;
using MediatR;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Knot.Modules.Relations.Application.Contacts.Integration;

internal sealed class UserRegisteredHandler : INotificationHandler<UserRegisteredDomainEvent>
{
    private readonly IContactsDbContext _context;

    public UserRegisteredHandler(IContactsDbContext context)
    {
        _context = context;
    }

    public async Task Handle(UserRegisteredDomainEvent notification, CancellationToken cancellationToken)
    {
        var existing = await _context.UserReplicas.AnyAsync(r => r.Id == notification.UserId, cancellationToken);
        if (existing) return;

        var replica = UserReplica.Create(
            notification.UserId,
            notification.Username,
            notification.DisplayName,
            string.Empty, // Avatar will be synced on update
            false,
            null
        );

        _context.UserReplicas.Add(replica);
        await _context.SaveChangesAsync(cancellationToken);
    }
}
