using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

namespace HorseRacingPredictor.Football.Database
{
    internal class Bookmaker : HorseRacingPredictor.Football.Manager.Database
    {
        public void Upsert(SqlConnection connection, JsonNode bookmaker)
        {
            try
            {
                var id = bookmaker["id"]?.GetValue<int>();
                if (id == null) return; // Salta il record se l'id è null

                var query = @"
                                IF EXISTS (SELECT 1 FROM Bookmaker WHERE bookmaker_id = @bookmaker_id)
                                BEGIN
                                    UPDATE Bookmaker SET name = @name WHERE bookmaker_id = @bookmaker_id
                                END
                                ELSE
                                BEGIN
                                    INSERT INTO Bookmaker (bookmaker_id, name) VALUES (@bookmaker_id, @name)
                                END";
                using (var command = new SqlCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@bookmaker_id", id);
                    command.Parameters.AddWithValue("@name", bookmaker["name"]?.GetValue<string>() ?? "");
                    command.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                LogError("l'upsert del bookmaker", ex);
            }
        }
    }
}
