using ProjectPatientAccounting.Entities.Enums;
using ProjectPatientAccounting.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Dapper;
namespace ProjectPatientAccounting.Repositories.Implementations;

public class MedicamentRepository : IMedicamentRepository
{
    private readonly IConnectionString _connectionString;
    private readonly ILogger<MedicamentRepository> _logger;

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

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

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

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

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

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

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