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

namespace HorseRacingPredictor.Football.Database
{
    internal class Team : HorseRacingPredictor.Football.Manager.Database
    {
        public void UpsertTeams(SqlConnection connection, SqlTransaction transaction, JsonNode teams, int fixtureId)
        {
            try
            {
                var homeTeamId = teams["home"]["id"]?.GetValue<int>();
                var awayTeamId = teams["away"]["id"]?.GetValue<int>();
                if (homeTeamId == null || awayTeamId == null) return; // Salta il record se uno degli id è null

                var queryTeam = @"
                            IF NOT EXISTS (SELECT 1 FROM Team WHERE team_id = @team_id)
                            BEGIN
                                INSERT INTO Team (team_id, name, logo) VALUES (@team_id, @name, @logo)
                            END
                            ELSE
                            BEGIN
                                UPDATE Team SET name = @name, logo = @logo WHERE team_id = @team_id
                            END";

                using (var command = new SqlCommand(queryTeam, connection, transaction))
                {
                    var homeTeam = teams["home"];
                    var awayTeam = teams["away"];

                    // Upsert home team
                    command.Parameters.AddWithValue("@team_id", homeTeamId);
                    command.Parameters.AddWithValue("@name", homeTeam["name"]?.GetValue<string>() ?? "");
                    command.Parameters.AddWithValue("@logo", homeTeam["logo"]?.GetValue<string>() ?? "");
                    command.ExecuteNonQuery();

                    // Upsert away team
                    command.Parameters["@team_id"].Value = awayTeamId;
                    command.Parameters["@name"].Value = awayTeam["name"]?.GetValue<string>() ?? "";
                    command.Parameters["@logo"].Value = awayTeam["logo"]?.GetValue<string>() ?? "";
                    command.ExecuteNonQuery();
                }

                // Aggiungiamo la relazione fixture-team solo se fixtureId è valido (non 0)
                if (fixtureId > 0)
                {
                    var queryFixtureTeam = @"
                        IF NOT EXISTS (SELECT 1 FROM FixtureTeams WHERE fixture_id = @fixture_id)
                        BEGIN
                            INSERT INTO FixtureTeams (fixture_id, home_team_id, away_team_id, home_winner, away_winner) 
                            VALUES (@fixture_id, @home_team_id, @away_team_id, NULL, NULL)
                        END
                        ELSE
                        BEGIN
                            UPDATE FixtureTeams SET home_team_id = @home_team_id, away_team_id = @away_team_id 
                            WHERE fixture_id = @fixture_id
                        END";

                    using (var command = new SqlCommand(queryFixtureTeam, connection, transaction))
                    {
                        // Upsert fixture-team relationship
                        command.Parameters.AddWithValue("@fixture_id", fixtureId);
                        command.Parameters.AddWithValue("@home_team_id", homeTeamId);
                        command.Parameters.AddWithValue("@away_team_id", awayTeamId);
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                LogError("l'upsert delle squadre", ex);
                throw; // Rilancia l'eccezione per il rollback della transazione
            }
        }
    }
}
