using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.ContractCQ.Commands.UpdateContract;
public class UpdateContractCommandHandler : IRequestHandler<UpdateContractCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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