#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.GetMyCustomerProfile;

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

        var dto = await unitOfWork.CustomerProfileRepository.GetMineAsync(userId, cancellationToken);
        return dto is null
            ? OperationResult<CustomerProfileDto>.NotFoundResult("No customer profile exists yet.")
            : OperationResult<CustomerProfileDto>.SuccessResult(dto);
    }
}
