|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Matches |
| 4 | + # Fetches match IDs from Riot API for a player and enqueues SyncMatchJob |
| 5 | + # for each new match. Returns counts synchronously so the caller can |
| 6 | + # respond with meaningful feedback without waiting for individual syncs. |
| 7 | + class ImportMatchesService |
| 8 | + def initialize(player:, organization:, count: 20, force_update: false) |
| 9 | + @player = player |
| 10 | + @organization = organization |
| 11 | + @count = count |
| 12 | + @force_update = force_update |
| 13 | + end |
| 14 | + |
| 15 | + # @return [Hash] counts: total_matches_found, imported, already_imported, updated |
| 16 | + def call |
| 17 | + match_ids = fetch_match_ids |
| 18 | + tally = { imported: 0, already_imported: 0, updated: 0 } |
| 19 | + |
| 20 | + match_ids.each { |id| process_match(id, tally) } |
| 21 | + |
| 22 | + tally.merge(total_matches_found: match_ids.size) |
| 23 | + end |
| 24 | + |
| 25 | + private |
| 26 | + |
| 27 | + def fetch_match_ids |
| 28 | + RiotApiService.new.get_match_history( |
| 29 | + puuid: @player.riot_puuid, |
| 30 | + region: region, |
| 31 | + count: @count |
| 32 | + ) |
| 33 | + end |
| 34 | + |
| 35 | + def process_match(match_id, tally) |
| 36 | + if Match.exists?(riot_match_id: match_id) |
| 37 | + handle_existing_match(match_id, tally) |
| 38 | + else |
| 39 | + SyncMatchJob.perform_later(match_id, @organization.id, region) |
| 40 | + tally[:imported] += 1 |
| 41 | + end |
| 42 | + end |
| 43 | + |
| 44 | + def handle_existing_match(match_id, tally) |
| 45 | + if @force_update |
| 46 | + SyncMatchJob.perform_later(match_id, @organization.id, region, force_update: true) |
| 47 | + tally[:updated] += 1 |
| 48 | + else |
| 49 | + tally[:already_imported] += 1 |
| 50 | + end |
| 51 | + end |
| 52 | + |
| 53 | + def region |
| 54 | + @player.region || 'BR' |
| 55 | + end |
| 56 | + end |
| 57 | +end |
0 commit comments