<?php

// src/Controller/DataImport.php
// Grab data from transfer app

namespace App\Controller\Routes\API;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use App\Service\Auth;
use App\Service\HandleLocations;

class Search extends AbstractController
{
    /**
     * @Route("/api/v1/search", name="api-saerch-locations")
     */
    public function handlePublicSearch(
        Request $request,
        Auth $auth,
        HandleLocations $locations
    ): Response {
        if ($request->getMethod() == "GET") {
            return new Response("LOL, nice try");
        } else {
            $encoders    = [new JsonEncoder()];
            $normalizers = [new ObjectNormalizer()];
            $serializer  = new Serializer($normalizers, $encoders);
            $response    = [];

            $data    = json_decode($request->getContent(), true);
            $list    = $locations->searchLocations(($data['url']));
            $entries = [];
            foreach ($list['items'] as $entry) {
                array_push($entries, ["url" => $entry['url'],
                    "name"                  => $entry['name'],
                    "description"           => $entry['description'],
                    "link"                  => "https://thebad.space/location/" . $entry['uuid']
                ]);
            }

            $items = ["listingCount" => count($entries), "locations" => $entries];

            $data     = $serializer->serialize($items, "json");
            $response = new Response($data);
            $response->headers->set("Content-Type", "application/json");
            return $response;
        }
    }
}
