using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectItCompany.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectItCompany.Repositories.Implementations;

public class WageRepository : IWageRepository
{
    private readonly IConnectionString _connectionString;
    private readonly ILogger<WageRepository> _logger;

    public WageRepository(IConnectionString connectionString, ILogger<WageRepository> logger)
    {
        _connectionString = connectionString;
        _logger = logger;
    }
    public void CreateWage(Wage wage)
    {
        _logger.LogInformation("Добавление объекта");
        _logger.LogDebug("Объект: {json}",
        JsonConvert.SerializeObject(wage));
        try
        {
            using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
            var queryInsert = @"INSERT INTO wage (Month, Year, NumberOfHours, ExecutorID)
                                VALUES (@Month, @Year, @NumberOfHours, @ExecutorID)";
            connection.Execute(queryInsert, wage);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Ошибка при добавлении объекта");
            throw;
        }

    }

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