<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\DocGeneratorBundle\Controller;

use Chill\DocGeneratorBundle\Context\ContextManager;
use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\MainBundle\Pagination\PaginatorInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class AdminDocGeneratorTemplateController extends CRUDController
{
    public function __construct(private readonly ContextManager $contextManager) {}

    public function generateTemplateParameter(string $action, $entity, Request $request, array $defaultTemplateParameters = [])
    {
        switch ($action) {
            case 'new':
                $context = $this->contextManager->getContextByKey($request->get('context'));
                // no break
            case 'edit':
                $context = $this->contextManager->getContextByDocGeneratorTemplate($entity);

                return array_merge(
                    $defaultTemplateParameters,
                    ['context' => $context]
                );

            case 'index':
                return array_merge(
                    $defaultTemplateParameters,
                    ['contextManager' => $this->contextManager]
                );

            default:
                return parent::generateTemplateParameter($action, $entity, $request, $defaultTemplateParameters); // TODO: Change the autogenerated stub
        }
    }

    public function new(Request $request): Response
    {
        if (!$request->query->has('context')) {
            return $this->redirectToRoute('chill_docgen_admin_template_pick-context');
        }

        return parent::new($request);
    }

    #[Route(path: '{_locale}/admin/docgen/template/pick-context', name: 'chill_docgen_admin_template_pick-context')]
    public function pickContext(Request $request): Response
    {
        $this->denyAccessUnlessGranted('ROLE_ADMIN');

        return $this->render('@ChillDocGenerator/DocGeneratorTemplate/pick-context.html.twig', [
            'contexts' => $this->contextManager->getContexts(),
        ]);
    }

    protected function createEntity(string $action, Request $request): object
    {
        /** @var DocGeneratorTemplate $entity */
        $entity = parent::createEntity($action, $request);
        $key = $request->query->get('context');
        $context = $this->contextManager->getContextByKey($key);

        $entity->setContext($key)->setEntity($context->getEntityClass());

        return $entity;
    }

    /**
     * @param QueryBuilder $query
     *
     * @return QueryBuilder|mixed
     */
    protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator)
    {
        return $query->addSelect('REPLACE(JSON_EXTRACT(e.name, :lang), \' \', \'~\') AS HIDDEN name_lang')
            ->setParameter('lang', $request->getLocale())
            ->addOrderBy('name_lang', 'ASC');
    }
}
