<?php

declare(strict_types=1);

namespace App\Repository;

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

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

    public function findLastForGame(Game $game): ?DartThrow
    {
        return $this->createQueryBuilder('th')
            ->innerJoin('th.turn', 't')
            ->where('th.game = :game')
            ->setParameter('game', $game)
            ->orderBy('t.turnNumber', 'DESC')
            ->addOrderBy('th.dartIndex', 'DESC')
            ->addOrderBy('th.id', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /** @return list<DartThrow> */
    public function findAllForGameOrdered(Game $game): array
    {
        return $this->createQueryBuilder('th')
            ->innerJoin('th.turn', 't')
            ->where('th.game = :game')
            ->setParameter('game', $game)
            ->orderBy('t.turnNumber', 'ASC')
            ->addOrderBy('th.dartIndex', 'ASC')
            ->addOrderBy('th.id', 'ASC')
            ->getQuery()
            ->getResult();
    }

    /** @return list<DartThrow> */
    public function findRecentForPlayer(GamePlayer $player, int $limit = 6): array
    {
        return $this->createQueryBuilder('th')
            ->innerJoin('th.turn', 't')
            ->where('th.player = :player')
            ->setParameter('player', $player)
            ->orderBy('t.turnNumber', 'DESC')
            ->addOrderBy('th.dartIndex', 'DESC')
            ->addOrderBy('th.id', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }
}
