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

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Chill\FranceTravailApiBundle\ApiHelper\PartenaireRomeAppellation;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

class RomeController extends AbstractController
{
    /**
     * @var PartenaireRomeAppellation
     */
    protected $apiAppellation;

    public function __construct(PartenaireRomeAppellation $apiAppellation)
    {
        $this->apiAppellation = $apiAppellation;
    }

    #[Route(path: '/{_locale}/france-travail/appellation/search.{_format}', name: 'chill_france_travail_api_appellation_search')]
    public function appellationSearchAction(Request $request)
    {
        if (false === $request->query->has('q')) {
            return new JsonResponse([]);
        }

        $appellations = $this->apiAppellation
            ->getListeAppellation($request->query->get('q'));
        $results = [];

        foreach ($appellations as $appellation) {
            $appellation['id'] = 'original-'.$appellation['code'];
            $appellation['text'] = $appellation['libelle'];
            $results[] = $appellation;
        }

        $computed = new \stdClass();
        $computed->pagination = (new \stdClass());
        $computed->pagination->more = false;
        $computed->results = $results;

        return new JsonResponse($computed);
    }
}
