All files / src/composables useLiveMatch.js

0% Statements 0/412
0% Branches 0/1
0% Functions 0/1
0% Lines 0/412

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
/**
 * 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';
 
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;
 
  // 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
    const firstHalfElapsed = (now - new Date(kickoff_time).getTime()) / 1000;
    return Math.min(firstHalfElapsed, halfDurationSeconds);
  });
 
  // Computed: formatted elapsed time (MM:SS)
  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')}`;
  });
 
  // 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);
      });
  }
 
  // Unsubscribe from Realtime
  function unsubscribeFromRealtime() {
    if (matchChannel) {
      supabase.removeChannel(matchChannel);
      matchChannel = null;
    }
    if (eventsChannel) {
      supabase.removeChannel(eventsChannel);
      eventsChannel = 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 postGoal(teamId, playerName, message = null, playerId = 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;
      }
 
      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) {
    try {
      const cardData = {
        team_id: teamId,
        player_id: playerId,
        card_type: cardType,
      };
      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 };
    }
  }
 
  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,
    matchPeriod,
    canManage,
 
    // Methods
    updateClock,
    postGoal,
    postCard,
    postMessage,
    deleteEvent,
    loadMoreEvents,
    fetchMatchState,
    fetchTeamRosters,
 
    // Lineup methods
    fetchLineup,
    fetchLineups,
    saveLineup,
  };
}