<?php

declare(strict_types=1);

namespace App\Controller;

use App\Dto\Input\DeleteMultipleClientsInput;
use App\Repository\ClientRepository;
use Doctrine\ORM\EntityManagerInterface;
use App\Controller\OgDhcp\Subnet\DeleteHostAction;
use App\Controller\OgBoot\PxeBootFile\DeleteAction;
use App\Entity\Client;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;

class DeleteMultipleClientsAction extends AbstractController
{
    public function __construct(
        private readonly ClientRepository $clientRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly KernelInterface $kernel,
        private readonly DeleteHostAction $deleteHostAction,
        private readonly DeleteAction $deletePxeAction,
    ) {
    }

    public function __invoke(DeleteMultipleClientsInput $input): JsonResponse
    {
        $errors = [];
        $deletedCount = 0;
        $totalCount = count($input->clients);

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

            try {
                
                if ($this->kernel->getEnvironment() !== 'test') {
                    if ($client->getSubnet()) {
                        $this->deleteHostAction->__invoke($client->getSubnet(), $client->getUuid()->toString());
                    }
                    $this->deletePxeAction->__invoke($client->getMac());
                }

                $this->clientRepository->delete($client);
                $deletedCount++;
            } catch (\Exception $e) {
                $errors[] = [
                    'client' => $client->getName() ?? $client->getUuid(),
                    'error' => $e->getMessage()
                ];
            }
        }

        $responseData = [
            'deleted' => $deletedCount,
            'total' => $totalCount,
            'success' => $deletedCount === $totalCount && empty($errors)
        ];

        if (!empty($errors)) {
            $responseData['errors'] = $errors;
        }

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

