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

internal sealed class GetBnplOrderStatusQueryHandler(
    IUnitOfWork unitOfWork,
    ICurrentUser currentUser)
    : IRequestHandler<GetBnplOrderStatusQuery, OperationResult<BnplOrderStatusDto>>
{
    public async ValueTask<OperationResult<BnplOrderStatusDto>> Handle(GetBnplOrderStatusQuery request, CancellationToken cancellationToken)
    {
        var projection = await unitOfWork.BnplRepository.GetStatusAsync(request.BnplTransactionId, cancellationToken);
        if (projection is null)
            return OperationResult<BnplOrderStatusDto>.NotFoundResult("BNPL order not found.");

        // Customer view: a cross-customer access is indistinguishable from "not found" — never confirm it exists.
        if (!request.AdminView && projection.CustomerUserId != currentUser.UserId)
            return OperationResult<BnplOrderStatusDto>.NotFoundResult("BNPL order not found.");

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