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 };
  }

  isTimeOut(state: GameState | null): boolean {
    if (!state?.clock) return false;
    return state.clock.whiteRemainingMs <= 0 || state.clock.blackRemainingMs <= 0;
  }

  private buildCompletionMessage(status: GameStatus, state: GameState, game: GameFull): string {
    const winner = state.winner === 'white' ? game.white.displayName : state.winner === 'black' ? game.black.displayName : null;
    const loser  = state.winner === 'white' ? game.black.displayName : state.winner === 'black' ? game.white.displayName : null;

    switch (status) {
      case 'checkmate':
        return winner ? `Checkmate — ${winner} wins!` : 'Checkmate!';
      case 'stalemate':
        return 'Stalemate — draw!';
      case 'resign':
        return loser && winner ? `${loser} resigned — ${winner} wins!` : 'Resigned.';
      case 'draw':
        return 'Draw by agreement.';
      case 'insufficientMaterial':
        return 'Draw — insufficient material.';
      default:
        return 'Game over.';
    }
  }
}
