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

namespace Baya.Application.Features.Bnpl.Queries.GetBnplOrderByRequest;

internal sealed class GetBnplOrderByRequestQueryHandler(
    ICurrentUser currentUser,
    IUnitOfWork unitOfWork)
    : IRequestHandler<GetBnplOrderByRequestQuery, OperationResult<BnplOrderStatusDto>>
{
    public async ValueTask<OperationResult<BnplOrderStatusDto>> Handle(GetBnplOrderByRequestQuery request, CancellationToken cancellationToken)
    {
        var projection = await unitOfWork.BnplRepository.GetStatusByRequestAsync(request.BookingRequestId, cancellationToken);

        // Cross-customer access is indistinguishable from "no order" — never leak another customer's order.
        if (projection is null || projection.CustomerUserId != currentUser.UserId)
            return OperationResult<BnplOrderStatusDto>.NotFoundResult("BNPL order not found.");

        return OperationResult<BnplOrderStatusDto>.SuccessResult(projection.Order);
    }
}
