<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\Game;
use App\Entity\User;
use App\Enum\GameStatus;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    public function findOwnedWithPlayers(string $id, User $owner): ?Game
    {
        return $this->createQueryBuilder('g')
            ->leftJoin('g.players', 'p')->addSelect('p')
            ->leftJoin('g.mode', 'm')->addSelect('m')
            ->where('g.id = :id')
            ->andWhere('g.owner = :owner')
            ->setParameter('id', $id)
            ->setParameter('owner', $owner)
            ->orderBy('p.position', 'ASC')
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function findWithPlayers(string $id): ?Game
    {
        return $this->createQueryBuilder('g')
            ->leftJoin('g.players', 'p')->addSelect('p')
            ->leftJoin('g.mode', 'm')->addSelect('m')
            ->where('g.id = :id')
            ->setParameter('id', $id)
            ->orderBy('p.position', 'ASC')
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * @return list<Game>
     */
    public function findByOwnerAndStatus(User $owner, GameStatus $status): array
    {
        return $this->createQueryBuilder('g')
            ->leftJoin('g.mode', 'm')->addSelect('m')
            ->andWhere('g.owner = :owner')
            ->andWhere('g.status = :status')
            ->setParameter('owner', $owner)
            ->setParameter('status', $status)
            ->orderBy('g.updatedAt', 'DESC')
            ->addOrderBy('g.createdAt', 'DESC')
            ->getQuery()
            ->getResult();
    }
}
