#nullable enable
using Baya.Application.Common;
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.ListPatients;

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

        var (page, pageSize) = Pagination.Normalize(request.Page, request.PageSize);

        var customerId = await unitOfWork.CustomerProfileRepository.GetProfileIdByUserIdAsync(userId, cancellationToken);
        if (customerId is not { } cid)
            return OperationResult<PagedResult<PatientDto>>.SuccessResult(new PagedResult<PatientDto>([], 0, page, pageSize));

        var result = await unitOfWork.PatientRepository.ListAsync(cid, page, pageSize, cancellationToken);
        return OperationResult<PagedResult<PatientDto>>.SuccessResult(result);
    }
}
