#nullable enable
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Mediator;

namespace Baya.Application.Features.Identity.Queries.GetMe;

internal sealed class GetMeQueryHandler(ICurrentUser currentUser, IUnitOfWork unitOfWork)
    : IRequestHandler<GetMeQuery, OperationResult<MeResult>>
{
    public async ValueTask<OperationResult<MeResult>> Handle(GetMeQuery request, CancellationToken cancellationToken)
    {
        if (currentUser.UserId is not { } userId)
            return OperationResult<MeResult>.UnauthorizedResult("Not authenticated.");

        var snapshot = await unitOfWork.UserAccountRepository.GetAccountSnapshotAsync(userId, cancellationToken);

        return snapshot is null
            ? OperationResult<MeResult>.NotFoundResult("User not found.")
            : OperationResult<MeResult>.SuccessResult(IdentityDefaults.ToMeResult(snapshot));
    }
}