<?php

namespace App\Controller\OgBoot\OgLive;

use App\Controller\OgBoot\AbstractOgBootController;
use App\Entity\OgLive;
use App\Model\OgLiveStatus;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
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 SyncAction extends AbstractOgBootController
{
    const string OG_BOOT_DIRECTORY = '/opt/opengnsys/ogboot/tftpboot//';

    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     * @throws \Exception
     */
    public function __invoke(): JsonResponse
    {
        $content = $this->createRequest('GET', '/ogboot/v1/oglives');

        if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR ) {
            throw new BadRequestHttpException('An error occurred while fetching ogLives: ' . $content['message'] . ' (' . $content['details'] . ')');
        }

        $allOgLives = $this->entityManager->getRepository(OgLive::class)->findAll();
        $apiChecksums = array_map(fn($ogLive) => $ogLive['id'], $content['message']['installed_ogLives']);

        foreach ($content['message']['installed_ogLives'] as $ogLive) {
            $ogLiveEntity = $this->entityManager->getRepository(OgLive::class)->findOneBy(['checksum' => $ogLive['id']]);

            if (!$ogLiveEntity) {
                $ogLiveEntity = $this->entityManager->getRepository(OgLive::class)->findOneBy(['filename' => str_replace(self::OG_BOOT_DIRECTORY, '', $ogLive['directory'])]);

                if (!$ogLiveEntity) {
                    $ogLiveEntity = new OgLive();
                }
            }
            $this->extracted($ogLiveEntity, $ogLive);
            $this->entityManager->persist($ogLiveEntity);
        }

        foreach ($allOgLives as $localOgLive) {
            if ($localOgLive->getStatus() === OgLiveStatus::PENDING ) {
                continue;
            }

            if (!in_array($localOgLive->getChecksum(), $apiChecksums)) {
                $this->entityManager->remove($localOgLive);
            }
        }

        $this->entityManager->flush();

        if (isset($content['message']['default_oglive'])) {
            $this->serDefaultOgLive($content['message']['default_oglive']);
        }

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

    /**
     * @param OgLive|null $ogLiveEntity
     * @param mixed $ogLive
     * @return void
     * @throws \Exception
     */
    private function extracted(OgLive $ogLiveEntity, mixed $ogLive): void
    {
        $name = $this->simplifyOgLiveFilenameService->__invoke(str_replace(self::OG_BOOT_DIRECTORY, '', $ogLive['directory']));

        $ogLiveEntity->setName($name ? $name : str_replace(self::OG_BOOT_DIRECTORY, '', $ogLive['directory']));
        $ogLiveEntity->setDate(new \DateTime($this->extractOgLiveFilenameDateService->__invoke(str_replace(self::OG_BOOT_DIRECTORY, '', $ogLive['directory']))));
        $ogLiveEntity->setInstalled(true);
        $ogLiveEntity->setArchitecture($ogLive['architecture']);
        $ogLiveEntity->setDistribution($ogLive['distribution']);
        $ogLiveEntity->setFilename(str_replace(self::OG_BOOT_DIRECTORY, '', $ogLive['directory']));
        $ogLiveEntity->setKernel($ogLive['kernel']);
        $ogLiveEntity->setRevision($ogLive['revision']);
        $ogLiveEntity->setDirectory($ogLive['directory']);
        $ogLiveEntity->setChecksum($ogLive['id']);
        $ogLiveEntity->setStatus(OgLiveStatus::ACTIVE);
    }

    private function serDefaultOgLive(string $defaultOgLive): void
    {
        $oldDefaultOgLive = $this->entityManager->getRepository(OgLive::class)->findAll();

        foreach ($oldDefaultOgLive as $oldOgLive) {
            $oldOgLive->setIsDefault(false);
            $this->entityManager->persist($oldOgLive);
        }

        $ogLiveEntity = $this->entityManager->getRepository(OgLive::class)->findOneBy(['filename' => $defaultOgLive]);

        if (!$ogLiveEntity) {
            return;
        }

        $ogLiveEntity->setIsDefault(true);
        $this->entityManager->persist($ogLiveEntity);
        $this->entityManager->flush();
    }
}