using Knot.Contracts.Conversations.Domain;
using Knot.Shared.Kernel;
using Knot.Contracts.Conversations.Application.Abstractions;

namespace Knot.Modules.Conversations.Application.Chats.GetOrCreateFavorites;

public sealed record GetOrCreateFavoritesCommand(Guid UserId) : ICommand<Guid>;

public sealed class GetOrCreateFavoritesCommandHandler : ICommandHandler<GetOrCreateFavoritesCommand, Guid>
{
    private readonly IChatRepository _chatRepository;
    private readonly IChatsUnitOfWork _unitOfWork;

    public GetOrCreateFavoritesCommandHandler(IChatRepository chatRepository, IChatsUnitOfWork unitOfWork)
    {
        _chatRepository = chatRepository;
        _unitOfWork = unitOfWork;
    }

    public async Task<Result<Guid>> Handle(GetOrCreateFavoritesCommand request, CancellationToken cancellationToken)
    {
        var favorites = await _chatRepository.GetFavoritesAsync(request.UserId, cancellationToken);

        if (favorites != null)
        {
            return Result.Success(favorites.Id);
        }

        // Create new favorites chat
        var chat = Chat.Create("Избранное", ChatType.Favorites);
        chat.AddMember(request.UserId, ChatRole.Owner);

        _chatRepository.Add(chat);
        await _unitOfWork.SaveChangesAsync(cancellationToken);

        return Result.Success(chat.Id);
    }
}

