using MediatR;
using IamService.Domain.AggregatesModel.GroupAggregate;
using IamService.Domain.Exceptions;

namespace IamService.API.Application.Commands.Groups;

/// <summary>
/// EN: Handler for DeleteGroupCommand.
/// VI: Handler cho DeleteGroupCommand.
/// </summary>
public class DeleteGroupCommandHandler : IRequestHandler<DeleteGroupCommand, bool>
{
    private readonly IGroupRepository _groupRepository;
    private readonly ILogger<DeleteGroupCommandHandler> _logger;

    public DeleteGroupCommandHandler(
        IGroupRepository groupRepository,
        ILogger<DeleteGroupCommandHandler> logger)
    {
        _groupRepository = groupRepository;
        _logger = logger;
    }

    public async Task<bool> Handle(DeleteGroupCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Deleting group: {Id}", request.Id);

        var group = await _groupRepository.GetByIdAsync(request.Id, cancellationToken);

        if (group == null)
        {
            throw new DomainException($"Group with ID '{request.Id}' not found.");
        }

        // EN: Soft delete
        // VI: Xóa mềm
        _groupRepository.Delete(group);

        await _groupRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("Group {Id} deleted successfully", request.Id);

        return true;
    }
}
