using MediatR;
using Modules.Media.Api.Commands;
using Modules.User.Application.Gateways;

namespace Modules.User.Application.Commands;


public class DeleteUserAvatarCommand : IRequest<Unit>
{
}

public class DeleteUserAvatarCommandHandler(UserContext userContext, IUserGateway userGateway, IMediator mediator) : IRequestHandler<DeleteUserAvatarCommand, Unit>
{
    public async Task<Unit> Handle(DeleteUserAvatarCommand request, CancellationToken cancellationToken)
    {

        var userInfo = await userContext.GetUserInfo(cancellationToken);
        //if (userInfo?.AccountId == null) throw new Exception("Account not found");
        if (userInfo?.AccountId == null) throw new Exception("User not found");
        var user = await userGateway.Get(userInfo.AccountId.Value) ?? throw new Exception("User was not found");
        if (!string.IsNullOrWhiteSpace(user.AvatarId))
        {
            var deleted = await mediator.Send(new DeleteObjectCommand
            {
                BusketName = "my-bookmark.user",
                ObjectName = user.AvatarId,
            }, cancellationToken);
            if (deleted)
            {
                user.SetAvatar(null);
                await userGateway.UpdateUser(user.Id, new Models.User
                {
                    NickName = user.NickName,
                    FirstName = user.FirstName,
                    Patronymic = user.Patronymic,
                    LastName = user.LastName,
                    LanguageId = user.LanguageId,
                }, user.AvatarId);
            }
        }

        return Unit.Value;
    }
}