using Netina.Domain.Entities.Orders;

namespace Netina.Repository.Handlers.Orders;

public class CreateBaseOrderCommandHandler(IRepositoryWrapper repositoryWrapper)
    : IRequestHandler<CreateBaseOrderCommand, Order>
{
    public async Task<Order> Handle(CreateBaseOrderCommand request, CancellationToken cancellationToken)
    {
        if (request.UserId == default)
            throw new AppException("Customer id is null");
        var customer = await repositoryWrapper.SetRepository<Customer>()
            .TableNoTracking
            .FirstOrDefaultAsync(c => c.UserId == request.UserId, cancellationToken);
        if (customer == null)
        {
            customer = new Customer
            {
                UserId = request.UserId
            };
            repositoryWrapper.SetRepository<Customer>()
                .Add(customer);
            await repositoryWrapper.SaveChangesAsync(cancellationToken);
        }
        var order = Order.Create(customer.Id);

        repositoryWrapper.SetRepository<Order>()
            .Add(order);

        await repositoryWrapper.SaveChangesAsync(cancellationToken);

        return order;
    }
}