using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Orders;

namespace Netina.Repository.Handlers.Orders;

public class CreateBaseOrderCommandHandler : IRequestHandler<CreateBaseOrderCommand,Order>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public CreateBaseOrderCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    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;
    }
}