<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\Game;
use App\Entity\GamePlayer;
use App\Entity\Turn;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<Turn>
 */
class TurnRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Turn::class);
    }

    public function findOpenTurn(Game $game): ?Turn
    {
        return $this->createQueryBuilder('t')
            ->where('t.game = :game')
            ->andWhere('t.endedAt IS NULL')
            ->setParameter('game', $game)
            ->orderBy('t.startedAt', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function findLastPlayerTurnIndex(GamePlayer $player): ?int
    {
        $value = $this->createQueryBuilder('t')
            ->select('MAX(t.playerTurnIndex)')
            ->where('t.player = :player')
            ->setParameter('player', $player)
            ->getQuery()
            ->getSingleScalarResult();

        return $value === null ? null : (int) $value;
    }

    public function findLastCompletedTurnForPlayer(Game $game, GamePlayer $player): ?Turn
    {
        return $this->createQueryBuilder('t')
            ->where('t.game = :game')
            ->andWhere('t.player = :player')
            ->andWhere('t.endedAt IS NOT NULL')
            ->setParameter('game', $game)
            ->setParameter('player', $player)
            ->orderBy('t.turnNumber', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }
}
