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

namespace FrymasterBadgeApp.Services;

public class SqlService
{
    private readonly string _connectionString;

    // Change constructor to accept string instead of IConfiguration
    public SqlService(string connectionString)
    {
        _connectionString = connectionString;

        if (string.IsNullOrEmpty(_connectionString))
        {
            AppLogger.Warn("SqlService: Initialized with an EMPTY connection string.");
        }
    }

    public List<Dictionary<string, object>> Query(string sql, SqlParameter[]? parameters = null)
    {
        var rows = new List<Dictionary<string, object>>();

        if (string.IsNullOrEmpty(_connectionString))
        {
            AppLogger.Warn(
                $"SqlService: Skipping Query because connection string is missing. SQL: {sql}"
            );
            return rows;
        }

        try
        {
            using var conn = new SqlConnection(_connectionString);
            using var cmd = new SqlCommand(sql, conn);

            if (parameters != null)
                cmd.Parameters.AddRange(parameters);

            AppLogger.Debug($"SqlService: Executing Query: {sql}");
            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);
            }
            AppLogger.Info($"SqlService: Query returned {rows.Count} rows.");
        }
        catch (Exception ex)
        {
            AppLogger.Error($"SqlService: Query execution failed for: {sql}", ex);
            // We re-throw here because this happens after the app has already started
            throw;
        }

        return rows;
    }

    public void Execute(string sql, SqlParameter[]? parameters = null)
    {
        if (string.IsNullOrEmpty(_connectionString))
        {
            AppLogger.Warn($"SqlService: Skipping Execute because connection string is missing.");
            return;
        }

        try
        {
            using var conn = new SqlConnection(_connectionString);
            using var cmd = new SqlCommand(sql, conn);

            if (parameters != null)
            {
                // Clear any previous ownership just in case
                cmd.Parameters.Clear();
                cmd.Parameters.AddRange(parameters);
            }

            AppLogger.Debug($"SqlService: Executing Command: {sql}");
            conn.Open();
            int affected = cmd.ExecuteNonQuery();
            AppLogger.Info($"SqlService: Execute finished. Rows affected: {affected}");

            // IMPORTANT: Clear parameters after execution so they can be reused if needed
            cmd.Parameters.Clear();
        }
        catch (Exception ex)
        {
            AppLogger.Error($"SqlService: Execute failed for: {sql}", ex);
            throw; // This will trigger the DisplayAlert in your Page
        }
    }
}
