using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserOrderCQ.Commands.CreateNewUserOrder;
public class CreateNewUserOrderCommandHandler : IRequestHandler<CreateNewUserOrderCommand, CreateNewUserOrderResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<CreateNewUserOrderResponseDto> Handle(CreateNewUserOrderCommand request,
        CancellationToken cancellationToken)
    {
        if (await _context.UserOrders.AnyAsync(x => x.UserId == request.UserId && x.PackageId == request.PackageId, cancellationToken: cancellationToken))
            throw new Exception(message: "duplicate order!!");

        var package = await _context.Packages
            .FirstOrDefaultAsync(x => x.Id == request.PackageId, cancellationToken) ?? throw new NotFoundException(nameof(Package), request.PackageId);

        var entity = request.Adapt<UserOrder>();
        entity.Amount = package.Price;
        await _context.UserOrders.AddAsync(entity, cancellationToken);
        entity.AddDomainEvent(new CreateNewUserOrderEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return entity.Adapt<CreateNewUserOrderResponseDto>();
    }
}
