<?php

namespace App\Controller\OgDhcp\Subnet;

use App\Controller\OgDhcp\AbstractOgDhcpController;
use App\Dto\Input\SubnetAddHostInput;
use App\Dto\Output\ClientOutput;
use App\Entity\Client;
use App\Entity\Subnet;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Validator\Exception\ValidatorException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

#[AsController]
class PostHostAction extends AbstractOgDhcpController
{

    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(SubnetAddHostInput $input, Subnet $subnet): JsonResponse
    {
        $clients = $input->clients;

        $success = [];
        $errors = [];

        foreach ($clients as $client) {
            /** @var Client $clientEntity */
            $clientEntity = $client->getEntity();

            $data = [
                'host' => $clientEntity->getName(),
                'macAddress' => strtolower($clientEntity->getMac()),
                'address' => $clientEntity->getIp(),
            ];

            $params = ['json' => $data];

            try {
                $content = $this->createRequest(
                    'POST',
                    'http://' . $this->ogDhcpApiUrl . '/ogdhcp/v1/subnets/' . $subnet->getServerId() . '/hosts',
                    $params
                );

                $success[] = [
                    'client' => $clientEntity->getName(),
                    'response' => $content
                ];

                $subnet->addClient($clientEntity);
                $this->entityManager->persist($subnet);
                $this->entityManager->flush();
            } catch (\Throwable $e) {
                $errors[] = [
                    'client' => $clientEntity->getName(),
                    'error' => $e->getMessage()
                ];
            }
        }

        return new JsonResponse(
            [
                'success' => $success,
                'errors' => $errors
            ],
            empty($errors) ? Response::HTTP_OK : Response::HTTP_MULTI_STATUS
        );
    }
}