<?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\PersonBundle\CRUD\Controller;

use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\PersonBundle\Entity\Person;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class OneToOneEntityPersonCRUDController extends CRUDController
{
    public function __construct(private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry) {}

    protected function generateRedirectOnCreateRoute($action, Request $request, $entity): string
    {
        throw new \BadMethodCallException('Not implemented yet.');
    }

    protected function getEntity($action, $id, Request $request): ?object
    {
        $entity = parent::getEntity($action, $id, $request);

        if (null === $entity) {
            $entity = $this->createEntity($action, $request);
            $person = $this->managerRegistry
                ->getManager()
                ->getRepository(Person::class)
                ->find($id);

            $entity->setPerson($person);
        }

        return $entity;
    }

    protected function getTemplateFor($action, $entity, Request $request)
    {
        if (!empty($this->crudConfig[$action]['template'])) {
            return $this->crudConfig[$action]['template'];
        }

        return match ($action) {
            'new' => '@ChillPerson/CRUD/new.html.twig',
            'edit' => '@ChillPerson/CRUD/edit.html.twig',
            'index' => '@ChillPerson/CRUD/index.html.twig',
            default => throw new \LogicException("the view for action {$action} is not ".'defined. You should override '.__METHOD__.' to add this action'),
        };
    }

    protected function onPostFetchEntity($action, Request $request, $entity): ?Response
    {
        if (false === $this->managerRegistry->getManager()->contains($entity)) {
            return new RedirectResponse($this->generateRedirectOnCreateRoute($action, $request, $entity));
        }

        return null;
    }

    protected function onPreFlush(string $action, $entity, FormInterface $form, Request $request)
    {
        $this->managerRegistry->getManager()->persist($entity);
    }
}
