# Code coverage report for composables/useWebSocket.ts

# All files / composables useWebSocket.ts

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

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

     /**
     * WebSocket Composable
     *
     * Manages Socket.io connection with type safety, authentication, and auto-reconnection.
     * This composable is league-agnostic and will be shared between SBA and PD frontends.
     *
     * Features:
     * - Type-safe Socket.io client (TypedSocket)
     * - JWT authentication integration
     * - Auto-reconnection with exponential backoff
     * - Connection status tracking
     * - Event listener lifecycle management
     * - Integration with game store
     */

    import { ref, computed, watch, onUnmounted } from 'vue'
    import { io, Socket } from 'socket.io-client'
    import type {
      TypedSocket,
      ClientToServerEvents,
      ServerToClientEvents,
    } from '~/types'
    import { useAuthStore } from '~/store/auth'
    import { useGameStore } from '~/store/game'
    import { useUiStore } from '~/store/ui'

    // Reconnection configuration
    const RECONNECTION_DELAY_BASE = 1000 // Start with 1 second
    const RECONNECTION_DELAY_MAX = 30000 // Max 30 seconds
    const MAX_RECONNECTION_ATTEMPTS = 10

    // Singleton socket instance
    let socketInstance: Socket<ServerToClientEvents, ClientToServerEvents> | null = null
    let reconnectionAttempts = 0
    let reconnectionTimeout: NodeJS.Timeout | null = null

    export function useWebSocket() {
      // ============================================================================
      // State
      // ============================================================================

      const isConnected = ref(false)
      const isConnecting = ref(false)
      const connectionError = ref<string | null>(null)
      const lastConnectionAttempt = ref<number | null>(null)

      // ============================================================================
      // Stores
      // ============================================================================

      const authStore = useAuthStore()
      const gameStore = useGameStore()
      const uiStore = useUiStore()

      // ============================================================================
      // Computed
      // ============================================================================

      const socket = computed((): TypedSocket | null => {
        return socketInstance as TypedSocket | null
      })

      const canConnect = computed(() => {
        return authStore.isAuthenticated && authStore.isTokenValid
      })

      const shouldReconnect = computed(() => {
        return (
          !isConnected.value &&
          canConnect.value &&
          reconnectionAttempts < MAX_RECONNECTION_ATTEMPTS
        )
      })

      // ============================================================================
      // Connection Management
      // ============================================================================

      /**
       * Connect to WebSocket server with JWT authentication
       */
      function connect() {
        if (!canConnect.value) {
          console.warn('[WebSocket] Cannot connect: not authenticated or token invalid')
          return
        }

        if (isConnected.value || isConnecting.value) {
          console.warn('[WebSocket] Already connected or connecting')
          return
        }

        isConnecting.value = true
        connectionError.value = null
        lastConnectionAttempt.value = Date.now()

        const config = useRuntimeConfig()
        const wsUrl = config.public.wsUrl

        console.log('[WebSocket] Connecting to', wsUrl)

        // Create or reuse socket instance
        if (!socketInstance) {
          socketInstance = io(wsUrl, {
            auth: {
              token: authStore.token,
            },
            autoConnect: false,
            reconnection: false, // We handle reconnection manually for better control
            transports: ['websocket', 'polling'],
          })

          setupEventListeners()
        } else {
          // Update auth token if reconnecting
          socketInstance.auth = {
            token: authStore.token,
          }
        }

        // Connect
        socketInstance.connect()
      }

      /**
       * Disconnect from WebSocket server
       */
      function disconnect() {
        console.log('[WebSocket] Disconnecting')

        // Clear reconnection timer
        if (reconnectionTimeout) {
          clearTimeout(reconnectionTimeout)
          reconnectionTimeout = null
        }

        // Disconnect socket
        if (socketInstance) {
          socketInstance.disconnect()
        }

        isConnected.value = false
        isConnecting.value = false
        connectionError.value = null
        reconnectionAttempts = 0
      }

      /**
       * Reconnect with exponential backoff
       */
      function scheduleReconnection() {
        if (!shouldReconnect.value) {
          console.log('[WebSocket] Reconnection not needed or max attempts reached')
          return
        }

        // Calculate delay with exponential backoff
        const delay = Math.min(
          RECONNECTION_DELAY_BASE * Math.pow(2, reconnectionAttempts),
          RECONNECTION_DELAY_MAX
        )

        console.log(
          `[WebSocket] Scheduling reconnection attempt ${reconnectionAttempts + 1}/${MAX_RECONNECTION_ATTEMPTS} in ${delay}ms`
        )

        reconnectionTimeout = setTimeout(() => {
          reconnectionAttempts++
          connect()
        }, delay)
      }

      // ============================================================================
      // Event Listeners Setup
      // ============================================================================

      /**
       * Set up all WebSocket event listeners
       */
      function setupEventListeners() {
        if (!socketInstance) return

        // ========================================
        // Connection Events
        // ========================================

        socketInstance.on('connect', () => {
          console.log('[WebSocket] Connected successfully')
          isConnected.value = true
          isConnecting.value = false
          connectionError.value = null
          reconnectionAttempts = 0

          // Update game store
          gameStore.setConnected(true)

          // Show success toast
          uiStore.showSuccess('Connected to game server')
        })

        socketInstance.on('disconnect', (reason) => {
          console.log('[WebSocket] Disconnected:', reason)
          isConnected.value = false
          isConnecting.value = false

          // Update game store
          gameStore.setConnected(false)

          // Show warning toast
          uiStore.showWarning('Disconnected from game server')

          // Attempt reconnection if not intentional
          if (reason !== 'io client disconnect') {
            scheduleReconnection()
          }
        })

        socketInstance.on('connect_error', (error) => {
          console.error('[WebSocket] Connection error:', error)
          isConnected.value = false
          isConnecting.value = false
          connectionError.value = error.message

          // Update game store
          gameStore.setError(error.message)

          // Show error toast
          uiStore.showError(`Connection failed: ${error.message}`)

          // Attempt reconnection
          scheduleReconnection()
        })

        socketInstance.on('connected', (data) => {
          console.log('[WebSocket] Server confirmed connection for user:', data.user_id)
        })

        socketInstance.on('heartbeat_ack', () => {
          // Heartbeat acknowledged - connection is healthy
          // No action needed, just prevents timeout
        })

        // ========================================
        // Game State Events
        // ========================================

        socketInstance.on('game_state_update', (state) => {
          console.log('[WebSocket] Game state update received')
          gameStore.setGameState(state)
        })

        socketInstance.on('game_state_sync', (data) => {
          console.log('[WebSocket] Full game state sync received')
          gameStore.setGameState(data.state)
          // Add recent plays to history
          data.recent_plays.forEach((play) => {
            gameStore.addPlayToHistory(play)
          })
        })

        socketInstance.on('play_completed', (play) => {
          console.log('[WebSocket] Play completed:', play.description)
          gameStore.addPlayToHistory(play)
          uiStore.showInfo(play.description, 3000)
        })

        socketInstance.on('inning_change', (data) => {
          console.log(`[WebSocket] Inning change: ${data.half} ${data.inning}`)
          uiStore.showInfo(`${data.half === 'top' ? 'Top' : 'Bottom'} ${data.inning}`, 3000)
        })

        socketInstance.on('game_ended', (data) => {
          console.log('[WebSocket] Game ended:', data.winner_team_id)
          uiStore.showSuccess(
            `Game Over! Final: ${data.final_score.away} - ${data.final_score.home}`,
            10000
          )
        })

        // ========================================
        // Decision Events
        // ========================================

        socketInstance.on('decision_required', (prompt) => {
          console.log('[WebSocket] Decision required:', prompt.phase)
          gameStore.setDecisionPrompt(prompt)
        })

        socketInstance.on('defensive_decision_submitted', (data) => {
          console.log('[WebSocket] Defensive decision submitted')
          gameStore.clearDecisionPrompt()
          if (data.pending_decision) {
            uiStore.showInfo('Defense set. Waiting for offense...', 3000)
          } else {
            uiStore.showSuccess('Defense set. Ready to play!', 3000)
          }
        })

        socketInstance.on('offensive_decision_submitted', (data) => {
          console.log('[WebSocket] Offensive decision submitted')
          gameStore.clearDecisionPrompt()
          uiStore.showSuccess('Offense set. Ready to play!', 3000)
        })

        // ========================================
        // Manual Workflow Events
        // ========================================

        socketInstance.on('dice_rolled', (data) => {
          console.log('[WebSocket] Dice rolled:', data.roll_id)
          gameStore.setPendingRoll({
            roll_id: data.roll_id,
            d6_one: data.d6_one,
            d6_two_a: 0, // Not provided by server
            d6_two_b: 0, // Not provided by server
            d6_two_total: data.d6_two_total,
            chaos_d20: data.chaos_d20,
            resolution_d20: data.resolution_d20,
            check_wild_pitch: data.check_wild_pitch,
            check_passed_ball: data.check_passed_ball,
            timestamp: data.timestamp,
          })
          uiStore.showInfo(data.message, 5000)
        })

        socketInstance.on('outcome_accepted', (data) => {
          console.log('[WebSocket] Outcome accepted:', data.outcome)
          gameStore.clearPendingRoll()
          uiStore.showSuccess('Outcome submitted. Resolving play...', 3000)
        })

        // ========================================
        // Substitution Events
        // ========================================

        socketInstance.on('player_substituted', (data) => {
          console.log('[WebSocket] Player substituted:', data.type)
          uiStore.showInfo(data.message, 5000)
          // Request updated lineup
          if (socketInstance) {
            socketInstance.emit('get_lineup', {
              game_id: gameStore.gameId!,
              team_id: data.team_id,
            })
          }
        })

        socketInstance.on('substitution_confirmed', (data) => {
          console.log('[WebSocket] Substitution confirmed')
          uiStore.showSuccess(data.message, 5000)
        })

        // ========================================
        // Data Response Events
        // ========================================

        socketInstance.on('lineup_data', (data) => {
          console.log('[WebSocket] Lineup data received for team:', data.team_id)
          gameStore.updateLineup(data.team_id, data.players)
        })

        socketInstance.on('box_score_data', (data) => {
          console.log('[WebSocket] Box score data received')
          // Box score will be handled by dedicated component
          // Just log for now
        })

        // ========================================
        // Error Events
        // ========================================

        socketInstance.on('error', (data) => {
          console.error('[WebSocket] Server error:', data.message)
          gameStore.setError(data.message)
          uiStore.showError(data.message, 7000)
        })

        socketInstance.on('outcome_rejected', (data) => {
          console.error('[WebSocket] Outcome rejected:', data.message)
          uiStore.showError(`Invalid outcome: ${data.message}`, 7000)
        })

        socketInstance.on('substitution_error', (data) => {
          console.error('[WebSocket] Substitution error:', data.message)
          uiStore.showError(`Substitution failed: ${data.message}`, 7000)
        })

        socketInstance.on('invalid_action', (data) => {
          console.error('[WebSocket] Invalid action:', data.reason)
          uiStore.showError(`Invalid action: ${data.reason}`, 7000)
        })

        socketInstance.on('connection_error', (data) => {
          console.error('[WebSocket] Connection error:', data.error)
          connectionError.value = data.error
          uiStore.showError(`Connection error: ${data.error}`, 7000)
        })
      }

      // ============================================================================
      // Heartbeat
      // ============================================================================

      /**
       * Send periodic heartbeat to keep connection alive
       */
      let heartbeatInterval: NodeJS.Timeout | null = null

      function startHeartbeat() {
        if (heartbeatInterval) return

        heartbeatInterval = setInterval(() => {
          if (socketInstance?.connected) {
            socketInstance.emit('heartbeat')
          }
        }, 30000) // Every 30 seconds
      }

      function stopHeartbeat() {
        if (heartbeatInterval) {
          clearInterval(heartbeatInterval)
          heartbeatInterval = null
        }
      }

      // ============================================================================
      // Watchers
      // ============================================================================

      // Auto-connect when authenticated
      watch(
        () => authStore.isAuthenticated,
        (authenticated) => {
          if (authenticated && !isConnected.value) {
            connect()
            startHeartbeat()
          } else if (!authenticated && isConnected.value) {
            disconnect()
            stopHeartbeat()
          }
        },
        { immediate: false }
      )

      // ============================================================================
      // Lifecycle
      // ============================================================================

      onUnmounted(() => {
        console.log('[WebSocket] Component unmounted, cleaning up')
        stopHeartbeat()
        // Don't disconnect on unmount - keep connection alive for app
        // Only disconnect when explicitly requested or user logs out
      })

      // ============================================================================
      // Public API
      // ============================================================================

      return {
        // State
        socket,
        isConnected: readonly(isConnected),
        isConnecting: readonly(isConnecting),
        connectionError: readonly(connectionError),
        canConnect,

        // Actions
        connect,
        disconnect,
      }
    }