using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.ContractCQ.Commands.DeleteContract;
public class DeleteContractCommandHandler : IRequestHandler<DeleteContractCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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