using MediatR;
using System.Threading;
using System.Threading.Tasks;
using Knot.Contracts.Profiles.Domain;
using Knot.Modules.Profiles.Domain;
using Knot.Shared.Kernel.Events;

namespace Knot.Modules.Profiles.Application.Profiles.Integration;

/// <summary>
/// Обработчик события из модуля Auth.
/// Создаёт пустой профиль при регистрации пользователя.
/// </summary>
public class UserRegisteredDomainEventHandler : INotificationHandler<UserRegisteredDomainEvent>
{
    private readonly IProfileRepository _repository;

    public UserRegisteredDomainEventHandler(IProfileRepository repository)
    {
        _repository = repository;
    }

    public async Task Handle(UserRegisteredDomainEvent notification, CancellationToken cancellationToken)
    {
        var profile = await _repository.GetAsync(notification.UserId, cancellationToken);
        if (profile != null)
            return;

        await _repository.CreateAsync(new Knot.Contracts.Profiles.Application.DTOs.UserProfileDto
        {
            UserId = notification.UserId,
            Username = notification.Username,
            DisplayName = notification.DisplayName ?? notification.Username
        }, cancellationToken);
    }
}
