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

namespace RealEstateTransactions.Repositories.Implementations
{
    public class PreSalesServicesRepository : IPreSalesServicesRepository
    {
        private readonly IConnectionString _connectionString;

        private readonly ILogger<PreSalesServicesRepository> _logger;

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

        public void CreatePreSalesService(PreSalesServices preSalesServices)
        {
            _logger.LogInformation("Добавление объекта");
            _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(preSalesServices));
            try
            {
                using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
                var insertQuery = @"
INSERT INTO Pre_Sales_Services (Apartment_ID, Name, Cost)
VALUES (@Apartment_ID, @Name, @Cost)";
                connection.Execute(insertQuery, preSalesServices);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка при добавлении объекта");
                throw;
            }
        }

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

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