#nullable enable
using Baya.Application.Common;
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Catalog;
using Baya.Application.Models.Common;
using Baya.Domain.Entities.User;
using Mediator;

namespace Baya.Application.Features.Variants.Queries.ListMyVariants;

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

        if (currentUser.Roles?.Contains(RoleNames.Nurse) != true)
            return OperationResult<PagedResult<VariantDto>>.ForbiddenResult("Only a nurse can view their variants.");

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

        var nurseId = await unitOfWork.NurseProfileRepository.GetProfileIdByUserIdAsync(userId, cancellationToken);
        if (nurseId is not { } nid)
            return OperationResult<PagedResult<VariantDto>>.SuccessResult(
                new PagedResult<VariantDto>([], 0, page, pageSize));

        var result = await unitOfWork.NurseServiceVariantRepository.ListMineAsync(nid, page, pageSize, cancellationToken);
        return OperationResult<PagedResult<VariantDto>>.SuccessResult(result);
    }
}
