<?php

declare(strict_types=1);

namespace App\Controller\OgAgent\Webhook;

use App\Entity\Client;
use App\Entity\OrganizationalUnit;
use App\Entity\Partition;
use App\Model\ClientStatus;
use App\Service\CreatePartitionService;
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\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Attribute\Route;

#[AsController]
class AgentController extends AbstractController
{
    public function __construct(
        protected readonly EntityManagerInterface $entityManager,
        protected readonly CreatePartitionService $createPartitionService
    )
    {
    }

    /**
     * @throws \Exception
     */
    #[Route('/opengnsys/rest/ogAdmClient/InclusionCliente', methods: ['POST'])]
    public function processClient(Request $request): JsonResponse
    {
        $data = $request->toArray();
        $requiredFields = ['iph', 'cfg'];

        foreach ($requiredFields as $field) {
            if (!isset($data[$field])) {
                return new JsonResponse(['message' => "Missing parameter: $field"], Response::HTTP_BAD_REQUEST);
            }
        }

        $clientEntity = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $data['iph']]);

        if (!$clientEntity) {
            return new JsonResponse(['message' => 'Client not found'], Response::HTTP_NOT_FOUND);
        }

        $clientEntity->setStatus(ClientStatus::OG_LIVE);
        $clientEntity->setToken($data['secret'] ?? null);
        $this->entityManager->persist($clientEntity);

        if (isset($data['cfg'])) {
            $this->createPartitionService->__invoke($data, $clientEntity);
        }
        
        $this->entityManager->flush();

        $center = $this->entityManager->getRepository(OrganizationalUnit::class)->find($clientEntity->getOrganizationalUnit()->getId());
        $root = $this->entityManager->getRepository(OrganizationalUnit::class)->getRootNodes();

        $responseData = [
            'res' => 1,
            'ido' => $clientEntity->getId(),
            'npc' => $clientEntity->getName(),
            'che' => 1,
            'exe' => 42,
            'ida' => $clientEntity->getOrganizationalUnit()?->getId(),
            'idc' => $root[0]->getId(),
        ];

        return new JsonResponse($responseData, Response::HTTP_OK);
    }


    #[Route('/opengnsys/rest/ogAdmClient/AutoexecCliente', methods: ['POST'])]
    public function autoexecCliente(Request $request): JsonResponse
    {
        $data = $request->toArray();
        $requiredFields = ['iph', 'exe'];

        $responseData = ['res' => 0];

        foreach ($requiredFields as $field) {
            if (!isset($data[$field])) {
                return new JsonResponse(['message' => "Missing parameter: $field"], Response::HTTP_BAD_REQUEST);
            }
        }

        $fileAutoExec = '/tmp/Sautoexec-' . $data['iph'];
        try {
            $fileExe = fopen($fileAutoExec, 'w');
            fwrite($fileExe, "nfn=popup\x0dtitle=my title\x0dmessage=my message");
            fclose($fileExe);
        } catch (\Exception $e) {
            return new JsonResponse([], Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        $responseData = [
            'res' => 1,
            'nfl' => $fileAutoExec
        ];

        return new JsonResponse($responseData, Response::HTTP_OK);
    }

    #[Route('/opengnsys/rest/ogAdmClient/enviaArchivo', methods: ['POST'])]
    public function enviaArchivo(Request $request): JsonResponse
    {
        $data = $request->toArray();
        $requiredFields = ['nfl'];

        foreach ($requiredFields as $field) {
            if (!isset($data[$field])) {
                return new JsonResponse(['message' => "Missing parameter: $field"], Response::HTTP_BAD_REQUEST);
            }
        }

        $nfl = $data['nfl'];
        //$nfl = $this->getParameter('kernel.project_dir') . '/file.txt';

        if (!file_exists($nfl)) {
            return new JsonResponse(['message' => 'File not found'], Response::HTTP_NOT_FOUND);
        }

        $contents = file_get_contents($nfl);

        return new JsonResponse(['contents' => base64_encode($contents)], Response::HTTP_OK);
    }

    #[Route('/opengnsys/rest/ogAdmClient/ComandosPendientes', methods: ['POST'])]
    public function comandosPendientes(Request $request): JsonResponse
    {
        $data = $request->toArray();
        $requiredFields = ['iph', 'ido'];

        foreach ($requiredFields as $field) {
            if (!isset($data[$field])) {
                return new JsonResponse(['message' => "Missing parameter: $field"], Response::HTTP_BAD_REQUEST);
            }
        }

        // Simula que el cliente existe
        if (!$this->clienteExistente($data['iph'])) {
            return new JsonResponse(['message' => 'Client not found'], Response::HTTP_NOT_FOUND);
        }

        // Simula obtener comandos pendientes
        $param = $this->buscaComandos($data['ido']);

        if (!$param) {
            return new JsonResponse(['nfn' => 'NoComandosPtes'], Response::HTTP_OK);
        }

        return new JsonResponse($param, Response::HTTP_OK);
    }

    #[Route('/opengnsys/rest/ogAdmClient/DisponibilidadComandos', methods: ['POST'])]
    public function disponibilidadComandos(Request $request): JsonResponse
    {
        $data = $request->toArray();
        $requiredFields = ['iph', 'tpc'];

        foreach ($requiredFields as $field) {
            if (!isset($data[$field])) {
                return new JsonResponse(['message' => "Missing parameter: $field"], Response::HTTP_BAD_REQUEST);
            }
        }

        if (!$this->clienteExistente($data['iph'])) {
            return new JsonResponse(['message' => 'Client not found'], Response::HTTP_NOT_FOUND);
        }

        return new JsonResponse(((object) null), Response::HTTP_OK);
    }

    private function clienteExistente($iph)
    {
        return true;
    }

    private function buscaComandos($ido): null
    {
        return null;
    }
}