using MediatR;
using Modules.User.Application.Gateways;
using Modules.User.Application.Models;

namespace Modules.User.Application.Queries;

public class GetUserAvatarQuery : IRequest<ObjectResult?>
{
}

public class GetUserAvatarQueryHandler(UserContext userContext, IUserGateway userGateway, IMediator mediator) : IRequestHandler<GetUserAvatarQuery, ObjectResult?>
{
    public async Task<ObjectResult?> Handle(GetUserAvatarQuery request, CancellationToken cancellationToken)
    {
        var userInfo = await userContext.GetUserInfo(cancellationToken);
        //if (userInfo?.AccountId == null) throw new Exception("User not found");
        if (userInfo?.AccountId == null) return null;
        var user = await userGateway.Get(userInfo.AccountId.Value) ?? throw new Exception("User was not found");
        if (string.IsNullOrWhiteSpace(user.AvatarId))
        {
            return null;
        }
        else
        {
            var result = await mediator.Send(new Media.Api.Queries.GetObjectQuery
            {
                BusketName = "my-bookmark.user",
                ObjectName = user.AvatarId,
            }, cancellationToken);
            return result == null ? null : new ObjectResult
            {
                ObjectName = result.ObjectName,
                ContentType = result.ContentType,
                Data = result.Data,
            };
        }
    }
}