<?php

declare(strict_types=1);

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\SaasBundle\Doctrine\Repository;

use Doctrine\ORM\Query;
use Doctrine\Persistence\ManagerRegistry;
use Serenity\CoreBundle\Seed\SeedPayload;
use Serenity\CoreBundle\Shared\Doctrine\Repository\BaseRepository;
use Serenity\SaasBundle\Entity\Project;
use Serenity\SaasBundle\Entity\Tenant;
use Symfony\Component\Security\Core\User\UserInterface;

final class ProjectRepository extends BaseRepository
{
    private const string ENTITY_CLASS = Project::class;

    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, self::ENTITY_CLASS);
    }

    /**
     * @return Project[]
     */
    public function getProjectsByTenant(Tenant|UserInterface $tenant): array
    {
        $qb = $this->createQueryBuilder('pj')
            ->andWhere('pj.tenant = :tenant')
            ->setParameter('tenant', $tenant);

        return $qb->getQuery()->getResult();
    }

    public function getProjectsByIdentifier(string $identifier): ?Project
    {
        $qb = $this->createQueryBuilder('pj')
            ->andWhere('pj.identifier = :identifier')
            ->setParameter('identifier', $identifier);

        return $qb->getQuery()->getOneOrNullResult();
    }

    public function getProjectByDomain(string $domain): ?Project
    {
        $qb = $this->createQueryBuilder('pj')
            ->orWhere('pj.domainIn = :domain')
            ->orWhere('pj.domainOut = :domain')
            ->setParameter('domain', $domain);

        return $qb->getQuery()->getOneOrNullResult();
    }

    /**
     * @return \Traversable<string> saasIdentifier
     */
    public function iterateForSeeding(SeedPayload $payload): \Traversable
    {
        $qb = $this->createQueryBuilder('p')
            ->select('p.saasIdentifier AS saasIdentifier')
            ->andWhere('p.saasIdentifier IS NOT NULL')
            ->orderBy('p.saasIdentifier', 'ASC');

        // Scope unique (contrat minimal)
        if (null !== $payload->saasIdentifier) {
            $qb->andWhere('p.saasIdentifier = :only')
                ->setParameter('only', $payload->saasIdentifier);
        }

        if ($payload->activeOnly) {
            $qb->andWhere('p.disabled = false');
        }

        if (null !== $payload->plan) {
            $qb->andWhere('p.plan = :plan')
                ->setParameter('plan', $payload->plan);
        }

        foreach ($qb->getQuery()->toIterable([], Query::HYDRATE_ARRAY) as $row) {
            /* @var array{saasIdentifier:string} $row */
            yield $row['saasIdentifier'];
        }
    }
}
