using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.TagCQ.Commands.DeleteTag;
public class DeleteTagCommandHandler : IRequestHandler<DeleteTagCommand, Unit>
{
    private readonly IApplicationDbContext _context;

    public DeleteTagCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<Unit> Handle(DeleteTagCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.Tags
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(Tag), request.Id);
        entity.IsDeleted = true;
        _context.Tags.Update(entity);
        entity.AddDomainEvent(new DeleteTagEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}

