# frozen_string_literal: true module EuchreCamp module Actions module Admin module Tournaments class SaveResults < EuchreCamp::Action include Deps[ events_repo: 'repositories.events', rounds_repo: 'repositories.tournament_rounds', matchups_repo: 'repositories.bracket_matchups', teams_repo: 'repositories.teams', matches_repo: 'repositories.matches' ] def handle(request, response) tournament_id = request.params[:id] params = request.params.to_h # Process each matchup result params.each do |key, value| key_str = key.to_s if key_str.start_with?('matchup_') matchup_id = key_str.gsub('matchup_', '').to_i team_1_score = params["team_1_score_#{matchup_id}"]&.to_i || 0 team_2_score = params["team_2_score_#{matchup_id}"]&.to_i || 0 matchup = matchups_repo.bracket_matchups.by_pk(matchup_id).one unless matchup && matchup[:team_1_id] && matchup[:team_2_id] next end # Create match record team_1 = teams_repo.teams.by_pk(matchup[:team_1_id]).one team_2 = teams_repo.teams.by_pk(matchup[:team_2_id]).one next if team_1.nil? || team_2.nil? match = matches_repo.create( event_id: tournament_id, team_1_p1_id: team_1.player_1_id, team_1_p2_id: team_1.player_2_id, team_2_p1_id: team_2.player_1_id, team_2_p2_id: team_2.player_2_id, team_1_score: team_1_score, team_2_score: team_2_score, status: 'completed' ) # Update matchup with match and winner winner_id = team_1_score > team_2_score ? matchup[:team_1_id] : matchup[:team_2_id] loser_id = team_1_score > team_2_score ? matchup[:team_2_id] : matchup[:team_1_id] matchups_repo.update(matchup_id, match_id: match[:id], winner_team_id: winner_id, loser_team_id: loser_id ) # Enqueue Elo calculation EuchreCamp::Jobs::CalculateEloJob.perform_later(match[:id]) end end response.flash[:message] = "Results saved" response.redirect_to("/admin/tournaments/#{tournament_id}") rescue StandardError => e response.flash[:error] = "Failed to save results: #{e.message}" response.redirect_to("/admin/tournaments/#{tournament_id}/results") end end end end end end