<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Entity\Installation;
use App\Kernel;
use App\Service\UpdateService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/updates')]
class UpdateController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly UpdateService $updateService,
    ) {}

    #[Route('', name: 'admin_updates', methods: ['GET'])]
    public function index(): Response
    {
        $installation = $this->entityManager->getRepository(Installation::class)->find(1);

        return $this->render('admin/updates/index.html.twig', [
            'currentVersion' => Kernel::VERSION,
            'installation' => $installation,
            'availableUpdate' => $installation ? $this->updateService->getAvailableUpdate($installation) : null,
        ]);
    }

    #[Route('/check', name: 'admin_updates_check', methods: ['POST'])]
    public function check(): Response
    {
        $installation = $this->entityManager->getRepository(Installation::class)->find(1);

        if ($installation) {
            $result = $this->updateService->checkForUpdate($installation);
            if ($result) {
                $this->addFlash('success', 'Yeni güncelleme mevcut: v' . $result['latest_version']);
            } else {
                $this->addFlash('info', 'Sisteminiz güncel.');
            }
        }

        return $this->redirectToRoute('admin_updates');
    }

    #[Route('/apply', name: 'admin_updates_apply', methods: ['POST'])]
    public function apply(): Response
    {
        $installation = $this->entityManager->getRepository(Installation::class)->find(1);

        if (!$installation) {
            $this->addFlash('error', 'Kurulum bilgisi bulunamadı.');
            return $this->redirectToRoute('admin_updates');
        }

        $update = $this->updateService->getAvailableUpdate($installation);
        if (!$update) {
            $this->addFlash('info', 'Güncelleme bulunamadı.');
            return $this->redirectToRoute('admin_updates');
        }

        $newVersion = $update['latest_version'];

        // ZIP indir
        $zipPath = $this->updateService->downloadUpdate($installation, $newVersion);
        if (!$zipPath) {
            $this->addFlash('error', 'Güncelleme dosyası indirilemedi. Lisansınızı kontrol edin.');
            return $this->redirectToRoute('admin_updates');
        }

        // Güncellemeyi uygula
        $result = $this->updateService->applyUpdate($zipPath, $newVersion);

        if ($result['success']) {
            $this->addFlash('success', $result['message']);
        } else {
            $this->addFlash('error', $result['message']);
        }

        return $this->redirectToRoute('admin_updates');
    }
}
