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

namespace Baya.Application.Features.PatientCareRecords.Queries.GetRecordAccess;

internal sealed class GetRecordAccessQueryHandler(
    ICurrentUser currentUser,
    IUnitOfWork unitOfWork)
    : IRequestHandler<GetRecordAccessQuery, OperationResult<RecordAccessDto>>
{
    public async ValueTask<OperationResult<RecordAccessDto>> Handle(GetRecordAccessQuery request, CancellationToken cancellationToken)
    {
        if (currentUser.UserId is null)
            return OperationResult<RecordAccessDto>.UnauthorizedResult("Not authenticated.");

        // Always 200 with the access flags (incl. the non-leaking not_found / not_authorized denied states) so
        // the client can render the access-denied card without probing a 403/404.
        var (_, access) = await PatientAccess.ResolveAsync(currentUser, unitOfWork, request.PatientId, cancellationToken);
        return OperationResult<RecordAccessDto>.SuccessResult(access);
    }
}
