using MediatR;
using MembershipService.Domain.AggregatesModel.LevelAggregate;

namespace MembershipService.API.Application.Commands;

/// <summary>
/// EN: Handler for deactivating a level definition (soft delete).
/// VI: Handler để vô hiệu hóa level definition (xóa mềm).
/// </summary>
public class DeactivateLevelDefinitionCommandHandler : IRequestHandler<DeactivateLevelDefinitionCommand, bool>
{
    private readonly ILevelDefinitionRepository _levelDefinitionRepository;
    private readonly ILogger<DeactivateLevelDefinitionCommandHandler> _logger;

    public DeactivateLevelDefinitionCommandHandler(
        ILevelDefinitionRepository levelDefinitionRepository,
        ILogger<DeactivateLevelDefinitionCommandHandler> logger)
    {
        _levelDefinitionRepository = levelDefinitionRepository ?? throw new ArgumentNullException(nameof(levelDefinitionRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<bool> Handle(DeactivateLevelDefinitionCommand request, CancellationToken cancellationToken)
    {
        // EN: Get level definition from repository
        // VI: Lấy level definition từ repository
        var levelDefinition = await _levelDefinitionRepository.GetAsync(request.Id);
        if (levelDefinition == null)
        {
            throw new KeyNotFoundException($"Level definition {request.Id} not found");
        }

        // EN: Soft delete by deactivating
        // VI: Xóa mềm bằng cách deactivate
        levelDefinition.Deactivate();

        _levelDefinitionRepository.Update(levelDefinition);
        await _levelDefinitionRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation(
            "Deactivated level definition {LevelId} with number {LevelNumber}",
            levelDefinition.Id, levelDefinition.LevelNumber);

        return true;
    }
}
