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

namespace Baya.Application.Features.Variants.Commands.SetVariantActive;

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

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

        var nurseId = await unitOfWork.NurseProfileRepository.GetProfileIdByUserIdAsync(userId, cancellationToken);
        if (nurseId is not { } nid)
            return OperationResult<bool>.NotFoundResult("Variant not found.");

        var variant = await unitOfWork.NurseServiceVariantRepository.GetOwnedAsync(request.Id, nid, cancellationToken);
        if (variant is null)
            return OperationResult<bool>.NotFoundResult("Variant not found.");

        variant.IsActive = request.IsActive;

        // Deactivate flips this variant's index rows to is_searchable=0 (kept, not deleted); activate makes
        // them searchable again — recomputed and staged in the same transaction as the toggle.
        await searchIndex.ReindexVariantAsync(variant, cancellationToken);
        await unitOfWork.CommitAsync();

        return OperationResult<bool>.SuccessResult(true);
    }
}
