using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectShoeShop.Entities;

namespace ProjectShoeShop.Repositories.Implementations;

public class OrderRepository : IOrderRepository
{
    private readonly IConnectionString _connectionString;
    private readonly ILogger<OrderRepository> _logger;

    public OrderRepository(IConnectionString connectionString, ILogger<OrderRepository> logger)
    {
        _connectionString = connectionString;
        _logger = logger;
    }

    public void CreateOrder(Order order)
    {
        _logger.LogInformation("Добавление объекта");
        _logger.LogDebug("Объект: {json}",
        JsonConvert.SerializeObject(order));
        try
        {
            using var connection = new
            NpgsqlConnection(_connectionString.ConnectionString);
            connection.Open();
            using var transaction = connection.BeginTransaction();
            var queryInsert = @"
                INSERT INTO ""Order"" (ClientId, OrderDate)
                VALUES (@ClientId, @OrderDate);
                SELECT MAX(Id) FROM ""Order""";
            var orderId =
            connection.QueryFirst<int>(queryInsert, order, transaction);
            var querySubInsert = @"
                INSERT INTO OrderItem (OrderId, ShoesId, NumberOfPairs, Size)
                VALUES (@OrderId, @ShoesId, @NumberOfPairs, @Size)";
            foreach (var elem in order.OrderItems)
            {
                connection.Execute(querySubInsert, new
                {
                    orderId,
                    elem.ShoesId,
                    elem.NumberOfPairs,
                    elem.Size
                }, transaction);
            }
            transaction.Commit();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Ошибка при добавлении объекта");
            throw;
        }
    }

    public IEnumerable<Order> ReadOrder(DateTime? dateForm = null, DateTime? dateTo = null)
    {
        _logger.LogInformation("Получение всех объектов");
        try
        {
            using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
            var querySelect = "SELECT * FROM \"Order\"";
            var contractorFuels = connection.Query<Order>(querySelect);
            _logger.LogDebug("Полученные объекты: {json}",
            JsonConvert.SerializeObject(contractorFuels));
            return contractorFuels;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Ошибка при чтении объектов");
            throw;
        }
    }
}
