<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Entity\Tenant\Category;
use App\Entity\Tenant\NewsAgencyConfig;
use App\Module\Agency\Service\AgencyManager;
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\Routing\Attribute\Route;

class AgencyController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly AgencyManager $agencyManager,
    ) {}

    /**
     * Ajans listesi - tum ajans konfigurasyonlarini gosterir.
     */
    #[Route('/agency', name: 'admin_agency')]
    public function index(): Response
    {
        $configs = $this->agencyManager->getAgencyConfigs();
        $adapters = $this->agencyManager->getAvailableAdapters();

        // Her ajans icin istatistikler
        $stats = [];
        foreach ($configs as $config) {
            $stats[$config->getAgencySlug()] = [
                'pending' => $this->agencyManager->getItemCount($config->getAgencySlug(), 'pending'),
                'imported' => $this->agencyManager->getItemCount($config->getAgencySlug(), 'imported'),
                'skipped' => $this->agencyManager->getItemCount($config->getAgencySlug(), 'skipped'),
                'total' => $this->agencyManager->getItemCount($config->getAgencySlug()),
            ];
        }

        return $this->render('admin/agency/index.html.twig', [
            'configs' => $configs,
            'adapters' => $adapters,
            'stats' => $stats,
        ]);
    }

    /**
     * Ajans konfigurasyonunu duzenle.
     */
    #[Route('/agency/{id}/edit', name: 'admin_agency_edit', methods: ['GET', 'POST'])]
    public function edit(int $id, Request $request): Response
    {
        $config = $this->agencyManager->getAgencyConfigById($id);
        if (!$config) {
            throw $this->createNotFoundException('Ajans konfigurasyonu bulunamadi.');
        }

        if ($request->isMethod('POST')) {
            if (!$this->isCsrfTokenValid('agency_form', $request->request->get('_token'))) {
                $this->addFlash('error', 'Gecersiz CSRF token.');

                return $this->redirectToRoute('admin_agency_edit', ['id' => $id]);
            }

            $this->handleFormData($config, $request);
            $this->agencyManager->saveConfig($config);

            $this->addFlash('success', $config->getAgencyName() . ' ayarlari basariyla guncellendi.');

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

        $categories = $this->entityManager->getRepository(Category::class)
            ->findBy(['status' => 'active'], ['title' => 'ASC']);

        return $this->render('admin/agency/form.html.twig', [
            'config' => $config,
            'categories' => $categories,
        ]);
    }

    /**
     * Ajans durumunu toggle et (aktif/pasif).
     */
    #[Route('/agency/{id}/toggle', name: 'admin_agency_toggle', methods: ['POST'])]
    public function toggle(int $id, Request $request): Response
    {
        $config = $this->agencyManager->getAgencyConfigById($id);
        if (!$config) {
            throw $this->createNotFoundException('Ajans konfigurasyonu bulunamadi.');
        }

        if (!$this->isCsrfTokenValid('toggle_agency_' . $id, $request->request->get('_token'))) {
            $this->addFlash('error', 'Gecersiz CSRF token.');

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

        $config->setIsActive(!$config->isActive());
        $this->agencyManager->saveConfig($config);

        $status = $config->isActive() ? 'aktif' : 'pasif';
        $this->addFlash('success', $config->getAgencyName() . ' ' . $status . ' edildi.');

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

    /**
     * Ajans baglantisini test et (AJAX).
     */
    #[Route('/agency/{id}/test', name: 'admin_agency_test', methods: ['POST'])]
    public function testConnection(int $id, Request $request): JsonResponse
    {
        $config = $this->agencyManager->getAgencyConfigById($id);
        if (!$config) {
            return new JsonResponse(['success' => false, 'message' => 'Ajans bulunamadi.'], 404);
        }

        $result = $this->agencyManager->testConnection($config);

        return new JsonResponse([
            'success' => $result,
            'message' => $result
                ? 'Baglanti basarili! API erisimi dogrulandi.'
                : 'Baglanti basarisiz. API URL ve anahtarini kontrol edin.',
        ]);
    }

    /**
     * Ajanstan haberleri cek.
     */
    #[Route('/agency/{id}/fetch', name: 'admin_agency_fetch', methods: ['POST'])]
    public function fetchNews(int $id, Request $request): Response
    {
        $config = $this->agencyManager->getAgencyConfigById($id);
        if (!$config) {
            throw $this->createNotFoundException('Ajans konfigurasyonu bulunamadi.');
        }

        if (!$this->isCsrfTokenValid('fetch_agency_' . $id, $request->request->get('_token'))) {
            $this->addFlash('error', 'Gecersiz CSRF token.');

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

        $items = $this->agencyManager->fetchNews($config);

        if (count($items) > 0) {
            $this->addFlash('success', count($items) . ' yeni haber cekildi (' . $config->getAgencyName() . ').');
        } else {
            $this->addFlash('info', 'Yeni haber bulunamadi (' . $config->getAgencyName() . ').');
        }

        return $this->redirectToRoute('admin_agency_items', ['slug' => $config->getAgencySlug()]);
    }

    /**
     * Ajans haberlerini listele.
     */
    #[Route('/agency/{slug}/items', name: 'admin_agency_items')]
    public function items(string $slug, Request $request): Response
    {
        $config = $this->agencyManager->getAgencyConfig($slug);
        if (!$config) {
            throw $this->createNotFoundException('Ajans bulunamadi.');
        }

        $status = $request->query->get('status');
        $page = max(1, $request->query->getInt('page', 1));
        $limit = 25;
        $offset = ($page - 1) * $limit;

        $items = $this->agencyManager->getItems($slug, $status, $limit, $offset);
        $totalCount = $this->agencyManager->getItemCount($slug, $status);
        $totalPages = (int) ceil($totalCount / $limit);

        $stats = [
            'pending' => $this->agencyManager->getItemCount($slug, 'pending'),
            'imported' => $this->agencyManager->getItemCount($slug, 'imported'),
            'skipped' => $this->agencyManager->getItemCount($slug, 'skipped'),
            'total' => $this->agencyManager->getItemCount($slug),
        ];

        return $this->render('admin/agency/items.html.twig', [
            'config' => $config,
            'items' => $items,
            'stats' => $stats,
            'currentStatus' => $status,
            'currentPage' => $page,
            'totalPages' => $totalPages,
            'totalCount' => $totalCount,
        ]);
    }

    /**
     * Tum bekleyen ajans haberlerini toplu import et.
     */
    #[Route('/agency/{slug}/import-all', name: 'admin_agency_import_all', methods: ['POST'])]
    public function importAll(string $slug, Request $request): Response
    {
        $config = $this->agencyManager->getAgencyConfig($slug);
        if (!$config) {
            throw $this->createNotFoundException('Ajans bulunamadi.');
        }

        if (!$this->isCsrfTokenValid('import_all_' . $slug, $request->request->get('_token'))) {
            $this->addFlash('error', 'Gecersiz CSRF token.');

            return $this->redirectToRoute('admin_agency_items', ['slug' => $slug]);
        }

        $importedCount = $this->agencyManager->importAllPending($slug);

        if ($importedCount > 0) {
            $this->addFlash('success', $importedCount . ' haber basariyla import edildi.');
        } else {
            $this->addFlash('info', 'Import edilecek bekleyen haber bulunamadi.');
        }

        return $this->redirectToRoute('admin_agency_items', ['slug' => $slug]);
    }

    /**
     * Ajans haberini import et (haber olarak kaydet).
     */
    #[Route('/agency/item/{id}/import', name: 'admin_agency_item_import', methods: ['POST'])]
    public function importItem(int $id, Request $request): Response
    {
        $item = $this->agencyManager->getItemById($id);
        if (!$item) {
            throw $this->createNotFoundException('Ajans haberi bulunamadi.');
        }

        if (!$this->isCsrfTokenValid('import_item_' . $id, $request->request->get('_token'))) {
            $this->addFlash('error', 'Gecersiz CSRF token.');

            return $this->redirectToRoute('admin_agency_items', ['slug' => $item->getAgencySlug()]);
        }

        $news = $this->agencyManager->importItem($item);

        if ($news) {
            $this->addFlash('success', '"' . $item->getTitle() . '" basariyla import edildi.');
        } else {
            $this->addFlash('error', 'Haber import edilemedi.');
        }

        return $this->redirectToRoute('admin_agency_items', ['slug' => $item->getAgencySlug()]);
    }

    /**
     * Ajans haberini atla.
     */
    #[Route('/agency/item/{id}/skip', name: 'admin_agency_item_skip', methods: ['POST'])]
    public function skipItem(int $id, Request $request): Response
    {
        $item = $this->agencyManager->getItemById($id);
        if (!$item) {
            throw $this->createNotFoundException('Ajans haberi bulunamadi.');
        }

        if (!$this->isCsrfTokenValid('skip_item_' . $id, $request->request->get('_token'))) {
            $this->addFlash('error', 'Gecersiz CSRF token.');

            return $this->redirectToRoute('admin_agency_items', ['slug' => $item->getAgencySlug()]);
        }

        $this->agencyManager->skipItem($item);
        $this->addFlash('success', 'Haber atlandi.');

        return $this->redirectToRoute('admin_agency_items', ['slug' => $item->getAgencySlug()]);
    }

    /**
     * Ajans haberi detayi (AJAX modal icin).
     */
    #[Route('/agency/item/{id}/detail', name: 'admin_agency_item_detail', methods: ['GET'])]
    public function itemDetail(int $id): Response
    {
        $item = $this->agencyManager->getItemById($id);
        if (!$item) {
            throw $this->createNotFoundException('Ajans haberi bulunamadi.');
        }

        return $this->render('admin/agency/item_detail.html.twig', [
            'item' => $item,
        ]);
    }

    private function handleFormData(NewsAgencyConfig $config, Request $request): void
    {
        $data = $request->request;

        $config->setIsActive((bool) $data->get('is_active', false));
        $config->setAutoPublish((bool) $data->get('auto_publish', false));
        $config->setFetchInterval((int) $data->get('fetch_interval', 15));

        $defaultCategoryId = $data->get('default_category_id');
        $config->setDefaultCategoryId($defaultCategoryId ? (int) $defaultCategoryId : null);

        // RSS ajansı icin ozel islem
        if ($config->getAgencySlug() === 'rss') {
            $this->handleRssFormData($config, $request);
        } else {
            // Ucretli ajanslar icin API bilgileri
            $config->setApiUrl($data->get('api_url') ?: null);
            $config->setApiKey($data->get('api_key') ?: null);
            $config->setApiSecret($data->get('api_secret') ?: null);

            // Ek konfigurasyonlar (JSON)
            $extraConfig = [];
            $filterCategories = $data->get('filter_categories');
            if ($filterCategories) {
                $extraConfig['filter_categories'] = array_filter(array_map('trim', explode(',', $filterCategories)));
            }
            $filterKeywords = $data->get('filter_keywords');
            if ($filterKeywords) {
                $extraConfig['filter_keywords'] = array_filter(array_map('trim', explode(',', $filterKeywords)));
            }
            $config->setConfig(!empty($extraConfig) ? $extraConfig : null);
        }
    }

    private function handleRssFormData(NewsAgencyConfig $config, Request $request): void
    {
        $data = $request->request;
        $extraConfig = $config->getConfig() ?? [];

        // Hazir feed'ler (JSON string olarak geliyor)
        $feedsJson = $data->get('rss_feeds_json');
        if ($feedsJson) {
            $feeds = json_decode($feedsJson, true);
            $extraConfig['feeds'] = is_array($feeds) ? $feeds : [];
        } else {
            $extraConfig['feeds'] = [];
        }

        // Ozel feed'ler (JSON string olarak geliyor)
        $customFeedsJson = $data->get('rss_custom_feeds_json');
        if ($customFeedsJson) {
            $customFeeds = json_decode($customFeedsJson, true);
            // Bos kaynaklari filtrele
            $extraConfig['custom_feeds'] = is_array($customFeeds)
                ? array_values(array_filter($customFeeds, fn($f) => !empty($f['url'])))
                : [];
        } else {
            $extraConfig['custom_feeds'] = [];
        }

        // Filtre ayarlari
        $filterKeywords = $data->get('filter_keywords');
        if ($filterKeywords) {
            $extraConfig['filter_keywords'] = array_filter(array_map('trim', explode(',', $filterKeywords)));
        }

        $filterCategories = $data->get('filter_categories');
        if ($filterCategories) {
            $extraConfig['filter_categories'] = array_filter(array_map('trim', explode(',', $filterCategories)));
        }

        $config->setConfig($extraConfig);
    }
}
