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

use Chill\MainBundle\Routing\ChillUrlGeneratorInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluation;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluationDocument;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodWorkVoter;
use Chill\PersonBundle\Service\AccompanyingPeriodWorkEvaluationDocument\AccompanyingPeriodWorkEvaluationDocumentDuplicator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

readonly class AccompanyingPeriodWorkEvaluationDocumentDuplicateController
{
    public function __construct(
        private AccompanyingPeriodWorkEvaluationDocumentDuplicator $duplicator,
        private Security $security,
        private SerializerInterface $serializer,
        private EntityManagerInterface $entityManager,
        private ChillUrlGeneratorInterface $urlGenerator,
    ) {}

    #[Route('/api/1.0/person/accompanying-course-work-evaluation-document/{id}/duplicate', methods: ['POST'])]
    public function duplicateApi(AccompanyingPeriodWorkEvaluationDocument $document): Response
    {
        $work = $document->getAccompanyingPeriodWorkEvaluation()->getAccompanyingPeriodWork();

        if (!$this->security->isGranted(AccompanyingPeriodWorkVoter::UPDATE, $work)) {
            throw new AccessDeniedHttpException('not allowed to edit this accompanying period work');
        }

        $duplicatedDocument = $this->duplicator->duplicate($document);

        $this->entityManager->persist($duplicatedDocument);
        $this->entityManager->persist($duplicatedDocument->getStoredObject());
        $this->entityManager->flush();

        return new JsonResponse(
            $this->serializer->serialize($duplicatedDocument, 'json', [AbstractNormalizer::GROUPS => ['read']]),
            json: true
        );
    }

    /**
     * @ParamConverter("document", options={"id": "document_id"})
     * @ParamConverter("evaluation", options={"id": "evaluation_id"})
     */
    #[Route('/api/1.0/person/accompanying-course-work-evaluation-document/{document_id}/evaluation/{evaluation_id}/duplicate', methods: ['POST'])]
    public function duplicateToEvaluationApi(AccompanyingPeriodWorkEvaluationDocument $document, AccompanyingPeriodWorkEvaluation $evaluation): Response
    {
        $work = $evaluation->getAccompanyingPeriodWork();

        if (!$this->security->isGranted(AccompanyingPeriodWorkVoter::UPDATE, $work)) {
            throw new AccessDeniedHttpException('not allowed to edit this accompanying period work');
        }

        $duplicatedDocument = $this->duplicator->duplicateToEvaluation($document, $evaluation);

        $this->entityManager->persist($duplicatedDocument);
        $this->entityManager->persist($duplicatedDocument->getStoredObject());
        $this->entityManager->persist($evaluation);
        $this->entityManager->flush();

        return new JsonResponse(
            $this->serializer->serialize($duplicatedDocument, 'json', [AbstractNormalizer::GROUPS => ['read']]),
            json: true
        );
    }

    #[Route('/{_locale}/person/accompanying-course-work-evaluation-document/{id}/duplicate', name: 'chill_person_accompanying_period_work_evaluation_document_duplicate', methods: ['POST'])]
    public function duplicate(AccompanyingPeriodWorkEvaluationDocument $document): Response
    {
        $work = $document->getAccompanyingPeriodWorkEvaluation()->getAccompanyingPeriodWork();

        if (!$this->security->isGranted(AccompanyingPeriodWorkVoter::UPDATE, $work)) {
            throw new AccessDeniedHttpException('not allowed to edit this accompanying period work');
        }

        $duplicatedDocument = $this->duplicator->duplicate($document);

        $this->entityManager->persist($duplicatedDocument);
        $this->entityManager->persist($duplicatedDocument->getStoredObject());
        $this->entityManager->flush();

        return new RedirectResponse(
            $this->urlGenerator->forwardReturnPath(
                'chill_person_accompanying_period_work_edit',
                ['id' => $work->getId(), 'doc_id' => $duplicatedDocument->getId()]
            )
        );
    }
}
