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

namespace Baya.Application.Features.Payouts.Queries.GetNursePayoutHistory;

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

        var page = request.Page < 1 ? 1 : request.Page;
        var pageSize = request.PageSize is < 1 or > 100 ? 20 : request.PageSize;

        // Tenancy: resolve the caller's own nurse profile — a caller who is not a nurse simply has no payouts.
        var nurseId = await unitOfWork.NurseProfileRepository.GetProfileIdByUserIdAsync(userId, cancellationToken);
        if (nurseId is not { } id)
            return OperationResult<PagedResult<NursePayoutHistoryDto>>.SuccessResult(
                new PagedResult<NursePayoutHistoryDto>([], 0, page, pageSize));

        var result = await unitOfWork.PayoutRepository.GetNurseHistoryAsync(id, page, pageSize, cancellationToken);
        return OperationResult<PagedResult<NursePayoutHistoryDto>>.SuccessResult(result);
    }
}
