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

namespace ProjectShoeShop.Repositories.Implementations;

public class ShoesRepository : IShoesRepository
{
    private readonly IConnectionString _connectionString;
    private readonly ILogger<ShoesRepository> _logger;

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

    public void CreateShoes(Shoes shoes)
    {
        _logger.LogInformation("Добавление объекта");
        _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(shoes));

        try
        {
            using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
            var queryInsert = @"
            INSERT INTO Shoes (Name, Price, ShoesType)
            VALUES (@Name, @Price, @ShoesType)";
            connection.Execute(queryInsert, shoes);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Ошибка при добавлении объекта");
            throw;
        }
    }

    public void DeleteShoes(int id)
    {
        _logger.LogInformation("Удаление объекта");
        _logger.LogDebug("Объект: {id}", id);
        try
        {
            using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
            var queryDelete = @"
                DELETE FROM Shoes
                WHERE Id=@id";
            connection.Execute(queryDelete, new { id });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Ошибка при удалении объекта");
            throw;
        }
    }

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

    public Shoes ReadShoesById(int id)
    {
        _logger.LogInformation("Получение объекта по идентификатору");
        _logger.LogDebug("Объект: {id}", id);
        try
        {
            using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
            var querySelect = @"
                SELECT * FROM Shoes
                WHERE Id=@id";
            var shoes = connection.QueryFirst<Shoes>(querySelect, new { id });
            _logger.LogDebug("Найденный объект: {json}",
                JsonConvert.SerializeObject(shoes));
            return shoes;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Ошибка при поиске объекта");
            throw;
        }
    }

    public void UpdateShoes(Shoes shoes)
    {
        _logger.LogInformation("Редактирование объекта");
        _logger.LogDebug("Объект: {json}",
            JsonConvert.SerializeObject(shoes));
        try
        {
            using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
            var queryUpdate = @"
                UPDATE Shoes
                SET
                Name=@Name,
                Price=@Price,
                ShoesType=@ShoesType
                WHERE Id=@Id";
            connection.Execute(queryUpdate, shoes);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Ошибка при редактировании объекта");
            throw;
        }
    }
}
