import { Injectable } from '@angular/core';
import { GameFull, GameState, GameStatus } from '../models/game.models';

export interface GameCompletion {
  isFinished: boolean;
  message: string;
}

@Injectable({ providedIn: 'root' })
export class GameCompletionService {
  getGameCompletion(game: GameFull | null, state: GameState | null): GameCompletion {
    if (!game || !state) {
      return { isFinished: false, message: '' };
    }

    const status = state.status;
    const gameEndingStatuses: GameStatus[] = ['checkmate', 'stalemate', 'resign', 'draw', 'insufficientMaterial'];

    if (!gameEndingStatuses.includes(status)) {
      return { isFinished: false, message: '' };
    }

    const message = this.buildCompletionMessage(status, state, game);
    return { isFinished: true, message };
  }

  private buildCompletionMessage(status: GameStatus, state: GameState, game: GameFull): string {
    switch (status) {
      case 'checkmate':
        const winner = state.winner === 'white' ? game.white.displayName : game.black.displayName;
        return `Checkmate! ${winner} wins!`;
      case 'stalemate':
        return 'Stalemate! The game is a draw.';
      case 'resign':
        const resignedPlayer = state.winner === 'white' ? game.black.displayName : game.white.displayName;
        const resignedWinner = state.winner === 'white' ? game.white.displayName : game.black.displayName;
        return `${resignedPlayer} resigned. ${resignedWinner} wins!`;
      case 'draw':
        return 'Draw! The game ended in a draw.';
      case 'insufficientMaterial':
        return 'Insufficient material! The game is a draw.';
      default:
        return 'Game ended!';
    }
  }
}
