All files / src/composables useLiveMatch.js

54.91% Statements 313/570
82% Branches 41/50
40% Functions 6/15
54.91% Lines 313/570

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 6421x 1x 1x 1x 1x 1x                 1x 1x   1x 13x   13x 13x 13x 13x 13x 13x   13x 13x 13x 13x   13x 13x 13x   13x 13x 13x   13x 13x 6x   6x 6x 6x 6x 6x 6x 6x 6x   6x 6x   6x 6x   6x 6x       6x   6x 6x 2x 2x 2x 2x   4x 6x       4x 4x 4x 4x 4x 13x   13x 13x 13x 13x 1x 1x 1x 1x 13x   13x 13x 13x 13x 13x 13x   13x 13x 13x 9x 9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 7x 9x   6x 6x   9x 2x 2x 4x 13x   13x 13x 13x 6x 5x 5x 5x 6x 6x 6x 13x   13x 13x 13x 6x 5x 6x 6x 6x 6x 6x 13x   13x 13x                               13x   13x 13x                                             13x   13x 13x 13x 13x 13x   13x 13x 13x   13x 4x 4x 4x 13x     13x 13x 13x 13x   13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x             13x 13x     13x   13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x               13x 13x 13x 13x 13x 13x 13x 13x 13x 13x                         13x 13x   13x   13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 5x 5x 13x 13x   13x 13x   13x 13x 13x 5x 2x 2x 2x 3x 3x 5x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 5x 5x 1x 5x 3x 3x 5x   13x 13x                               13x 13x 13x 13x   13x 13x   13x 13x             13x   13x                                                           13x                                 13x                                                                                         13x                                                                               13x                                       13x                             13x                             13x 13x 13x 13x 13x 13x   13x 13x     13x   13x 13x 13x 13x             13x   13x 13x 13x 13x 13x 13x 13x 13x 13x 13x   13x 13x   13x 13x 13x 13x 13x 13x 13x   13x 13x 13x 13x   13x 13x 13x 13x 13x 13x 13x 13x 13x   13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x   13x 13x 13x 13x 13x 13x  
/**
 * Live Match Composable
 *
 * Provides reactive state and methods for live match functionality.
 * Uses Supabase Realtime for push updates of match state and events.
 */
 
import { ref, computed, onUnmounted, watch } from 'vue';
import { supabase } from '../config/supabase';
import { useAuthStore } from '../stores/auth';
import { getApiBaseUrl } from '../config/api';
import { useMatchLineup } from './useMatchLineup';
import { mergeEventWindow } from '../utils/liveEvents';
 
// How many of the newest events a chat re-read fetches (SB-1329).
const CHAT_REFRESH_LIMIT = 50;
 
export function useLiveMatch(matchId) {
  const authStore = useAuthStore();
 
  // Reactive state
  const matchState = ref(null);
  const events = ref([]);
  const isLoading = ref(true);
  const error = ref(null);
  const isConnected = ref(false);
 
  // Supabase channels
  let matchChannel = null;
  let eventsChannel = null;
  let chatChannel = null;
 
  // Chat re-reads are coalesced: rings during a fetch trigger one more.
  let chatRefreshing = false;
  let chatRefreshPending = false;
 
  // Clock update interval
  let clockInterval = null;
  const currentTime = ref(Date.now());
 
  // Computed: elapsed time in seconds based on timestamps
  const elapsedSeconds = computed(() => {
    if (!matchState.value) return 0;
 
    const {
      kickoff_time,
      halftime_start,
      second_half_start,
      match_end_time,
      match_status,
      half_duration = 45, // Default to 45 minutes per half
    } = matchState.value;
 
    const halfDurationSeconds = half_duration * 60;
    const fullMatchSeconds = half_duration * 2 * 60;
 
    // Match not started
    if (!kickoff_time) return 0;
 
    // Match ended - show full match time
    if (match_end_time || match_status === 'completed') {
      return fullMatchSeconds;
    }
 
    const now = currentTime.value;
 
    // In second half
    if (second_half_start) {
      const secondHalfElapsed =
        (now - new Date(second_half_start).getTime()) / 1000;
      return halfDurationSeconds + secondHalfElapsed;
    }
 
    // At halftime
    if (halftime_start && !second_half_start) {
      return halfDurationSeconds;
    }
 
    // In first half. SB-67: we no longer cap at halfDurationSeconds —
    // the clock keeps counting past 45:00 so the consumer can detect
    // and display stoppage time.
    const firstHalfElapsed = (now - new Date(kickoff_time).getTime()) / 1000;
    return firstHalfElapsed;
  });
 
  // Computed: formatted elapsed time (MM:SS). Retained for any consumer
  // that wants the raw clock without stoppage notation; the recommended
  // display surface is `clockDisplayFormatted` below.
  const elapsedTimeFormatted = computed(() => {
    const totalSeconds = Math.floor(elapsedSeconds.value);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  });
 
  // ── SB-67: Stoppage time ──
  // Once the elapsed clock crosses the half_duration boundary (45:00 by
  // default), we're in stoppage. The badge + the `45+M:SS` formatting in
  // `clockDisplayFormatted` are driven off these three computeds. The
  // backend already records `extra_time` on goals/cards via
  // `calculate_match_minute()` — this is purely a display layer.
 
  // True only when actively playing past the regulation boundary. False
  // during halftime, at fulltime, before kickoff.
  const isInStoppage = computed(() => {
    if (!matchState.value) return false;
    const {
      kickoff_time,
      halftime_start,
      second_half_start,
      match_end_time,
      match_status,
      half_duration = 45,
    } = matchState.value;
 
    if (!kickoff_time) return false;
    if (match_end_time || match_status === 'completed') return false;
    // At halftime (clock paused between halves) — not stoppage.
    if (halftime_start && !second_half_start) return false;
 
    const halfDurationSeconds = half_duration * 60;
    const fullMatchSeconds = halfDurationSeconds * 2;
 
    if (second_half_start) {
      return elapsedSeconds.value > fullMatchSeconds;
    }
    return elapsedSeconds.value > halfDurationSeconds;
  });
 
  // Seconds past the current period's regulation boundary. 0 outside
  // stoppage.
  const stoppageElapsedSeconds = computed(() => {
    if (!isInStoppage.value) return 0;
    const { second_half_start, half_duration = 45 } = matchState.value;
    const halfDurationSeconds = half_duration * 60;
    const boundary = second_half_start
      ? halfDurationSeconds * 2
      : halfDurationSeconds;
    return Math.max(0, elapsedSeconds.value - boundary);
  });
 
  // Authoritative display string: regulation `MM:SS`, stoppage `45+M:SS`
  // (or `90+M:SS` in the 2nd half).
  const clockDisplayFormatted = computed(() => {
    if (!isInStoppage.value) return elapsedTimeFormatted.value;
    const { second_half_start, half_duration = 45 } = matchState.value;
    const baseMinutes = second_half_start ? half_duration * 2 : half_duration;
    const stoppageWhole = Math.floor(stoppageElapsedSeconds.value);
    const minutes = Math.floor(stoppageWhole / 60);
    const seconds = stoppageWhole % 60;
    return `${baseMinutes}+${minutes}:${seconds.toString().padStart(2, '0')}`;
  });
 
  // Computed: match period
  const matchPeriod = computed(() => {
    if (!matchState.value) return 'Not Started';
 
    const {
      kickoff_time,
      halftime_start,
      second_half_start,
      match_end_time,
      match_status,
    } = matchState.value;
 
    if (match_end_time || match_status === 'completed') return 'Full Time';
    if (second_half_start) return '2nd Half';
    if (halftime_start) return 'Halftime';
    if (kickoff_time) return '1st Half';
    return 'Not Started';
  });
 
  // Computed: can the current user manage this match?
  const canManage = computed(() => {
    if (!matchState.value) return false;
    if (!authStore.isAuthenticated.value) return false;
 
    // Admins can manage all
    if (authStore.isAdmin.value) return true;
 
    // Club managers can manage their club's teams
    if (authStore.isClubManager.value) {
      // This would need club_id check - for now allow
      return true;
    }
 
    // Team managers can manage their team's matches
    if (authStore.isTeamManager.value) {
      const userTeamId = authStore.userTeamId.value;
      return (
        userTeamId === matchState.value.home_team_id ||
        userTeamId === matchState.value.away_team_id
      );
    }
 
    return false;
  });
 
  // Fetch initial match state
  async function fetchMatchState() {
    try {
      isLoading.value = true;
      error.value = null;
 
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/live`
      );
 
      if (response) {
        matchState.value = response;
        events.value = response.recent_events || [];
      }
    } catch (err) {
      console.error('Error fetching match state:', err);
      error.value = err.message || 'Failed to load match';
    } finally {
      isLoading.value = false;
    }
  }
 
  // Subscribe to Supabase Realtime
  function subscribeToRealtime() {
    // Subscribe to match changes
    matchChannel = supabase
      .channel(`match:${matchId}`)
      .on(
        'postgres_changes',
        {
          event: 'UPDATE',
          schema: 'public',
          table: 'matches',
          filter: `id=eq.${matchId}`,
        },
        payload => {
          console.log('Match update received:', payload);
          // Merge updated fields into match state
          if (matchState.value) {
            matchState.value = { ...matchState.value, ...payload.new };
          }
        }
      )
      .subscribe(status => {
        isConnected.value = status === 'SUBSCRIBED';
        console.log('Match channel status:', status);
      });
 
    // Subscribe to new events
    eventsChannel = supabase
      .channel(`match_events:${matchId}`)
      .on(
        'postgres_changes',
        {
          event: 'INSERT',
          schema: 'public',
          table: 'match_events',
          filter: `match_id=eq.${matchId}`,
        },
        payload => {
          console.log('New event received:', payload);
          // Check if event already exists (avoid duplicates from optimistic updates)
          const exists = events.value.some(e => e.id === payload.new.id);
          if (!exists) {
            events.value = [payload.new, ...events.value].slice(0, 100);
          }
        }
      )
      .on(
        'postgres_changes',
        {
          event: 'UPDATE',
          schema: 'public',
          table: 'match_events',
          filter: `match_id=eq.${matchId}`,
        },
        payload => {
          console.log('Event update received:', payload);
          // Update the event (for soft deletes)
          const index = events.value.findIndex(e => e.id === payload.new.id);
          if (index !== -1) {
            // If deleted, remove from list
            if (payload.new.is_deleted) {
              events.value = events.value.filter(e => e.id !== payload.new.id);
            } else {
              events.value[index] = payload.new;
            }
          }
        }
      )
      .subscribe(status => {
        console.log('Events channel status:', status);
      });
 
    // Chat (SB-1329): clients cannot read chat rows, so the events channel
    // above only carries goals, cards and status changes. The backend touches
    // live_chat_signals whenever this match's chat changes; re-read it then.
    // A separate channel, so a problem here never stops the score streaming.
    chatChannel = supabase
      .channel(`live_chat_signals:${matchId}`)
      .on(
        'postgres_changes',
        {
          event: '*',
          schema: 'public',
          table: 'live_chat_signals',
          filter: `match_id=eq.${matchId}`,
        },
        () => {
          refreshChat();
        }
      )
      .subscribe(status => {
        console.log('Chat signal channel status:', status);
      });
  }
 
  // Re-read the newest events through the API, which applies blocks, and
  // merge them in (SB-1329).
  async function refreshChat() {
    if (chatRefreshing) {
      chatRefreshPending = true;
      return;
    }
    chatRefreshing = true;
    try {
      do {
        chatRefreshPending = false;
        const response = await authStore.apiRequest(
          `${getApiBaseUrl()}/api/matches/${matchId}/live/events?limit=${CHAT_REFRESH_LIMIT}`
        );
        if (Array.isArray(response)) {
          events.value = mergeEventWindow(
            events.value,
            response,
            CHAT_REFRESH_LIMIT
          );
        }
      } while (chatRefreshPending);
    } catch (err) {
      console.error('Error refreshing chat:', err);
    } finally {
      chatRefreshing = false;
    }
  }
 
  // Unsubscribe from Realtime
  function unsubscribeFromRealtime() {
    if (matchChannel) {
      supabase.removeChannel(matchChannel);
      matchChannel = null;
    }
    if (eventsChannel) {
      supabase.removeChannel(eventsChannel);
      eventsChannel = null;
    }
    if (chatChannel) {
      supabase.removeChannel(chatChannel);
      chatChannel = null;
    }
    isConnected.value = false;
  }
 
  // Start clock update interval
  function startClockInterval() {
    if (clockInterval) clearInterval(clockInterval);
    clockInterval = setInterval(() => {
      currentTime.value = Date.now();
    }, 1000);
  }
 
  // Stop clock update interval
  function stopClockInterval() {
    if (clockInterval) {
      clearInterval(clockInterval);
      clockInterval = null;
    }
  }
 
  // API Methods
 
  async function updateClock(actionOrPayload, halfDuration = null) {
    try {
      // Handle both string action and object payload
      let payload;
      if (typeof actionOrPayload === 'object') {
        payload = actionOrPayload;
      } else {
        payload = { action: actionOrPayload };
        if (halfDuration) {
          payload.half_duration = halfDuration;
        }
      }
 
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/live/clock`,
        {
          method: 'POST',
          body: JSON.stringify(payload),
        }
      );
      if (response) {
        matchState.value = response;
      }
      return { success: true };
    } catch (err) {
      console.error('Error updating clock:', err);
      return { success: false, error: err.message };
    }
  }
 
  async function reopenMatch() {
    try {
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/live/reopen`,
        { method: 'POST' }
      );
      if (response) {
        matchState.value = response;
        await fetchMatchState();
      }
      return { success: true };
    } catch (err) {
      console.error('Error reopening match:', err);
      return { success: false, error: err.message };
    }
  }
 
  async function postGoal(
    teamId,
    playerName,
    message = null,
    playerId = null,
    assistPlayerId = null
  ) {
    try {
      const goalData = {
        team_id: teamId,
        message,
      };
 
      // Prefer player_id (from roster) over player_name (legacy free-text)
      if (playerId) {
        goalData.player_id = playerId;
      } else if (playerName) {
        goalData.player_name = playerName;
      }
 
      // Optional by design — most goals have no assist. The API only accepts a
      // roster player, so a free-text scorer can never carry one.
      if (assistPlayerId) {
        goalData.assist_player_id = assistPlayerId;
      }
 
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/live/goal`,
        {
          method: 'POST',
          body: JSON.stringify(goalData),
        }
      );
      if (response) {
        matchState.value = response;
        // Refetch events to get the new goal event
        await fetchMatchState();
      }
      return { success: true };
    } catch (err) {
      console.error('Error posting goal:', err);
      return { success: false, error: err.message };
    }
  }
 
  async function postCard(
    teamId,
    playerId,
    cardType,
    message = null,
    playerName = null
  ) {
    try {
      const cardData = {
        team_id: teamId,
        card_type: cardType,
      };
      if (playerId != null) {
        cardData.player_id = playerId;
      }
      if (playerName) {
        cardData.player_name = playerName;
      }
      if (message) {
        cardData.message = message;
      }
 
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/live/card`,
        {
          method: 'POST',
          body: JSON.stringify(cardData),
        }
      );
      // Refetch events to get the new card event
      if (response) {
        await fetchMatchState();
      }
      return { success: true };
    } catch (err) {
      console.error('Error posting card:', err);
      return { success: false, error: err.message };
    }
  }
 
  async function postMessage(message) {
    try {
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/live/message`,
        {
          method: 'POST',
          body: JSON.stringify({ message }),
        }
      );
      // Add event to local state immediately (don't wait for Realtime)
      if (response && response.id) {
        events.value = [response, ...events.value].slice(0, 100);
      }
      return { success: true, event: response };
    } catch (err) {
      console.error('Error posting message:', err);
      return { success: false, error: err.message, status: err.status };
    }
  }
 
  async function deleteEvent(eventId) {
    try {
      await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/live/events/${eventId}`,
        { method: 'DELETE' }
      );
      // Remove from local state immediately
      events.value = events.value.filter(e => e.id !== eventId);
      return { success: true };
    } catch (err) {
      console.error('Error deleting event:', err);
      return { success: false, error: err.message };
    }
  }
 
  async function loadMoreEvents(beforeId) {
    try {
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/live/events?before_id=${beforeId}&limit=50`
      );
      if (response && Array.isArray(response)) {
        events.value = [...events.value, ...response];
      }
      return { success: true };
    } catch (err) {
      console.error('Error loading more events:', err);
      return { success: false, error: err.message };
    }
  }
 
  // Initialize on mount
  async function initialize() {
    await fetchMatchState();
    subscribeToRealtime();
    startClockInterval();
  }
 
  // Cleanup on unmount
  onUnmounted(() => {
    unsubscribeFromRealtime();
    stopClockInterval();
  });
 
  // Watch for matchId changes (if used dynamically)
  watch(
    () => matchId,
    newId => {
      if (newId) {
        unsubscribeFromRealtime();
        stopClockInterval();
        initialize();
      }
    }
  );
 
  // Delegate roster/lineup operations to shared composable
  const {
    homeLineup,
    awayLineup,
    lineupLoading,
    fetchTeamRosters,
    fetchLineup,
    fetchLineups,
    saveLineup,
  } = useMatchLineup(matchId, matchState);
 
  // Auto-initialize
  initialize();
 
  return {
    // State
    matchState,
    events,
    isLoading,
    error,
    isConnected,
 
    // Lineup state
    homeLineup,
    awayLineup,
    lineupLoading,
 
    // Computed
    elapsedSeconds,
    elapsedTimeFormatted,
    // SB-67: stoppage-time display surface.
    isInStoppage,
    stoppageElapsedSeconds,
    clockDisplayFormatted,
    matchPeriod,
    canManage,
 
    // Methods
    updateClock,
    reopenMatch,
    postGoal,
    postCard,
    postMessage,
    deleteEvent,
    loadMoreEvents,
    fetchMatchState,
    fetchTeamRosters,
    refreshChat,
 
    // Lineup methods
    fetchLineup,
    fetchLineups,
    saveLineup,
  };
}