<?php

/*
 * 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\Twig\Components;

use Serenity\CoreBundle\Shared\Common\UserInterface;
use Serenity\SaasBundle\Doctrine\Repository\ProjectRepository;
use Serenity\SaasBundle\Entity\Project;
use Serenity\SaasBundle\Entity\Tenant;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent(template: '@components/SerenitySaas/SelectProject.html.twig')]
class SelectProject extends AbstractController
{
    use ComponentToolsTrait;
    use DefaultActionTrait;

    /** @var Project[] */
    public array $projects = [];

    public function __construct(private readonly ProjectRepository $projectRepository, private readonly RequestStack $requestStack)
    {
    }

    public function mount(): void
    {
        $user = $this->getUser();

        if (!$user instanceof UserInterface) {
            return;
        }

        $this->projects = $this->projectRepository->getProjectsByTenant($user);
    }

    #[LiveAction]
    public function select(#[LiveArg] Project $project, #[LiveArg] Tenant $tenant): Response
    {
        if ($project->getTenant() !== $tenant) {
            return $this->redirectToRoute('admin_saas_select_project');
        }

        $this->requestStack->getSession()->set('project_identifier', $project->getIdentifier());

        return $this->redirectToRoute('admin_index');
    }

    #[LiveAction]
    public function reactivate(#[LiveArg] Project $project): void
    {
    }
}
