<?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\Entity\PostalCode;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\Query;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

/**
 * Class PostalCodeController.
 */
class PostalCodeController extends AbstractController
{
    /**
     * @var TranslatableStringHelper
     */
    protected $translatableStringHelper;

    public function __construct(TranslatableStringHelper $translatableStringHelper, private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry)
    {
        $this->translatableStringHelper = $translatableStringHelper;
    }

    /**
     * @return JsonResponse
     */
    #[Route(path: '{_locale}/postalcode/search')]
    public function searchAction(Request $request)
    {
        $pattern = $request->query->getAlnum('q', '');

        if (empty($pattern)) {
            return new JsonResponse(['results' => [], 'pagination' => ['more' => false]]);
        }

        $query = $this->managerRegistry->getManager()
            ->createQuery(
                sprintf(
                    'SELECT p.id AS id, p.name AS name, p.code AS code, '
                    .'country.name AS country_name, '
                    .'country.countryCode AS country_code '
                    .'FROM %s p '
                    .'JOIN p.country country '
                    .'WHERE LOWER(p.name) LIKE LOWER(:pattern) OR LOWER(p.code) LIKE LOWER(:pattern) '
                    .'ORDER BY code',
                    PostalCode::class
                )
            )
            ->setParameter('pattern', '%'.$pattern.'%')
            ->setMaxResults(30);

        $results = \array_map(function ($row) {
            $row['country_name'] = $this->translatableStringHelper->localize($row['country_name']);
            $row['text'] = $row['code'].' '.$row['name'].' ('.$row['country_name'].')';

            return $row;
        }, $query->getResult(Query::HYDRATE_ARRAY));

        return new JsonResponse(['results' => $results, 'pagination' => ['more' => false]]);
    }
}
