using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;

namespace FrymasterBadgeApp.Services;

public class SqlService
{
    private readonly string _connectionString;

    public SqlService(IConfiguration configuration)
    {
        // Pulls the "Default" string from your JSON structure
        _connectionString =
            configuration.GetConnectionString("Default")
            ?? throw new Exception("Connection string 'Default' not found in appsettings.json");
    }

    public List<Dictionary<string, object>> Query(string sql, SqlParameter[]? parameters = null)
    {
        var rows = new List<Dictionary<string, object>>();
        using var conn = new SqlConnection(_connectionString);
        using var cmd = new SqlCommand(sql, conn);
        if (parameters != null)
            cmd.Parameters.AddRange(parameters);

        conn.Open();
        using var reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            var row = new Dictionary<string, object>();
            for (int i = 0; i < reader.FieldCount; i++)
            {
                row[reader.GetName(i)] = reader.GetValue(i);
            }
            rows.Add(row);
        }
        return rows;
    }

    public void Execute(string sql, SqlParameter[]? parameters = null)
    {
        using var conn = new SqlConnection(_connectionString);
        using var cmd = new SqlCommand(sql, conn);
        if (parameters != null)
            cmd.Parameters.AddRange(parameters);
        conn.Open();
        cmd.ExecuteNonQuery();
    }
}
