<?php

namespace App\Controller\Admin;

use App\Entity\Domain;
use App\Entity\Website;
use App\Service\MeilisearchService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/admin/services', name: 'app_admin_services_')]
#[IsGranted('ROLE_EMPLOYE')]
class ServicesController extends AbstractController
{
    #[Route('', name: 'index')]
    public function index(): Response
    {
        return $this->render('admin/services/index.html.twig');
    }

    #[Route('/ndd', name: 'ndd')]
    public function ndd(EntityManagerInterface $em): Response
    {
        $domains = $em->getRepository(Domain::class)->findBy([], ['fqdn' => 'ASC']);

        return $this->render('admin/services/ndd.html.twig', [
            'domains' => $domains,
        ]);
    }

    #[Route('/ndd/search', name: 'ndd_search', methods: ['GET'])]
    public function nddSearch(Request $request, MeilisearchService $meilisearch): JsonResponse
    {
        $q = trim($request->query->getString('q'));

        return new JsonResponse('' === $q ? [] : $meilisearch->searchDomains($q));
    }

    #[Route('/esyweb', name: 'esyweb')]
    public function esyweb(EntityManagerInterface $em): Response
    {
        $websites = $em->getRepository(Website::class)->findBy([], ['createdAt' => 'DESC']);

        return $this->render('admin/services/esyweb.html.twig', [
            'websites' => $websites,
        ]);
    }

    #[Route('/esyweb/search', name: 'esyweb_search', methods: ['GET'])]
    public function esywebSearch(Request $request, MeilisearchService $meilisearch): JsonResponse
    {
        $q = trim($request->query->getString('q'));

        return new JsonResponse('' === $q ? [] : $meilisearch->searchWebsites($q));
    }
}
