import { ITurnHistoryRepository } from '../../Domain/IRepository/ITurnHistoryRepository'; import { TurnHistoryAggregate, TurnActionType, TurnActionData } from '../../Domain/Game/TurnHistoryAggregate'; import { logOther, logError } from './Logger'; export class TurnHistoryService { constructor(private turnHistoryRepository: ITurnHistoryRepository) {} /** * Log a turn action */ async logTurnAction( gameId: string, playerId: string, playerName: string, turnNumber: number, actionType: TurnActionType, positionBefore: number, positionAfter: number, actionData?: TurnActionData ): Promise { try { const turnHistory = new TurnHistoryAggregate(); turnHistory.gameid = gameId; turnHistory.playerid = playerId; turnHistory.playername = playerName; turnHistory.turnNumber = turnNumber; turnHistory.actionType = actionType; turnHistory.positionBefore = positionBefore; turnHistory.positionAfter = positionAfter; turnHistory.actionData = actionData || null; await this.turnHistoryRepository.save(turnHistory); logOther(`Turn history logged: ${actionType}`, { gameId, playerId, playerName, turnNumber, positionBefore, positionAfter }); } catch (error) { logError('Failed to log turn history', error as Error); // Don't throw - logging shouldn't break game flow } } /** * Get game replay data */ async getGameReplay(gameId: string): Promise { return await this.turnHistoryRepository.findByGameId(gameId); } /** * Get player's turn history in a game */ async getPlayerHistory(gameId: string, playerId: string): Promise { return await this.turnHistoryRepository.findByGameAndPlayer(gameId, playerId); } /** * Get recent turns for a game */ async getRecentTurns(gameId: string, limit: number = 10): Promise { return await this.turnHistoryRepository.findLastNTurns(gameId, limit); } /** * Clean up turn history for a finished game */ async cleanupGameHistory(gameId: string): Promise { try { await this.turnHistoryRepository.deleteByGameId(gameId); logOther(`Turn history cleaned up for game ${gameId}`); } catch (error) { logError('Failed to cleanup turn history', error as Error); } } }