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

use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\MainBundle\Entity\Address;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;

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

    /**
     * Duplicate an existing address.
     */
    #[Route(path: '/api/1.0/main/address/{id}/duplicate.json', name: 'chill_api_main_address_duplicate', methods: ['POST'])]
    public function duplicate(Address $address): JsonResponse
    {
        $this->denyAccessUnlessGranted('ROLE_USER');
        $new = Address::createFromAddress($address);

        $em = $this->managerRegistry->getManager();

        $em->persist($new);
        $em->flush();

        return $this->json($new, Response::HTTP_OK, [], [
            AbstractNormalizer::GROUPS => ['read'],
        ]);
    }
}
