using System;
using System.Data.SqlClient;
using System.Text.Json.Nodes;

namespace HorseRacingPredictor.Football.Database
{
    internal class Goals : HorseRacingPredictor.Football.Manager.Database
    {
        public void Upsert(SqlConnection connection, JsonNode goals, int fixtureId)
        {
            try
            {
                // Utilizza la tabella Score invece di una tabella Goals che non esiste
                var query = @"
                                IF EXISTS (SELECT 1 FROM Score WHERE fixture_id = @fixture_id)
                                BEGIN
                                    UPDATE Score SET home_goals = @home, away_goals = @away WHERE fixture_id = @fixture_id
                                END
                                ELSE
                                BEGIN
                                    INSERT INTO Score (home_goals, away_goals, fixture_id, 
                                                      home_halftime, away_halftime, 
                                                      home_fulltime, away_fulltime, 
                                                      home_extratime, away_extratime, 
                                                      home_penalty, away_penalty) 
                                    VALUES (@home, @away, @fixture_id, 0, 0, 0, 0, 0, 0, 0, 0)
                                END";
                using (var command = new SqlCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@home", goals["home"]?.GetValue<int?>() ?? 0);
                    command.Parameters.AddWithValue("@away", goals["away"]?.GetValue<int?>() ?? 0);
                    command.Parameters.AddWithValue("@fixture_id", fixtureId);
                    command.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                LogError("l'upsert dei goal", ex);
            }
        }
    }
}
