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

namespace Baya.Application.Features.Verification.Queries.GetStatus;

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

        if (currentUser.Roles?.Contains(RoleNames.Nurse) != true)
            return OperationResult<VerificationStatusDto>.ForbiddenResult("Only a nurse can read their verification.");

        var nurseId = await unitOfWork.NurseProfileRepository.GetProfileIdByUserIdAsync(userId, cancellationToken);
        if (nurseId is not { } id)
            return OperationResult<VerificationStatusDto>.NotFoundResult("No nurse profile exists yet.");

        var status = await unitOfWork.VerificationRepository.GetStatusForNurseAsync(id, cancellationToken);

        // No verification row yet — return the empty "not started" checklist so the client can prompt submit.
        status ??= new VerificationStatusDto(VerificationStatus.NotStarted.ToCode(), false, [], []);

        return OperationResult<VerificationStatusDto>.SuccessResult(status);
    }
}
