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

namespace Baya.Application.Features.PartnerCenters.Commands.SetPartnerCenterActive;

internal sealed class SetPartnerCenterActiveCommandHandler(IUnitOfWork unitOfWork)
    : IRequestHandler<SetPartnerCenterActiveCommand, OperationResult<PartnerCenterDetailDto>>
{
    public async ValueTask<OperationResult<PartnerCenterDetailDto>> Handle(SetPartnerCenterActiveCommand request, CancellationToken cancellationToken)
    {
        var center = await unitOfWork.PartnerCenterRepository.GetTrackedAsync(request.Id, cancellationToken);
        if (center is null)
            return OperationResult<PartnerCenterDetailDto>.NotFoundResult("Partner center not found.");

        center.SetActive(request.IsActive);
        await unitOfWork.CommitAsync();

        var detail = await unitOfWork.PartnerCenterRepository.GetDetailAsync(center.Id, cancellationToken);
        return OperationResult<PartnerCenterDetailDto>.SuccessResult(detail!);
    }
}
