<?php

namespace App\Controller\Admin;

use App\Repository\PriceAutomaticRepository;
use App\Service\MeilisearchService;
use App\Service\StripePriceService;
use App\Service\TarificationService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/admin/tarification', name: 'app_admin_tarification')]
#[IsGranted('ROLE_ROOT')]
class TarificationController extends AbstractController
{
    private const TARIF_PREFIX = 'Tarif "';

    #[Route('', name: '')]
    public function index(TarificationService $tarification): Response
    {
        $created = $tarification->ensureDefaultPrices();
        foreach ($created as $type) {
            $this->addFlash('success', self::TARIF_PREFIX.$type.'" cree automatiquement.');
        }

        return $this->render('admin/tarification/index.html.twig', [
            'prices' => $tarification->getAll(),
        ]);
    }

    #[Route('/{id}/edit', name: '_edit', methods: ['POST'])]
    public function edit(
        int $id,
        Request $request,
        PriceAutomaticRepository $repository,
        EntityManagerInterface $em,
        StripePriceService $stripePriceService,
        MeilisearchService $meilisearch,
    ): Response {
        $price = $repository->find($id);

        if (null === $price) {
            throw $this->createNotFoundException('Tarif introuvable.');
        }

        $price->setTitle(trim($request->request->getString('title')));
        $price->setDescription(trim($request->request->getString('description')) ?: null);
        $price->setPriceHt($request->request->getString('priceHt'));
        $price->setMonthPrice($request->request->getString('monthPrice'));
        $price->setPeriod((int) $request->request->getString('period'));
        $price->setStripeId(trim($request->request->getString('stripeId')) ?: null);
        $price->setStripeAbonnementId(trim($request->request->getString('stripeAbonnementId')) ?: null);

        $em->flush();

        // Sync Stripe
        try {
            $stripePriceService->syncPrice($price);
            $this->addFlash('success', self::TARIF_PREFIX.$price->getType().'" mis a jour et synchronise avec Stripe.');
        } catch (\Throwable $e) {
            $em->flush();
            $this->addFlash('success', self::TARIF_PREFIX.$price->getType().'" mis a jour.');
            $this->addFlash('error', 'Erreur Stripe : '.$e->getMessage());
        }

        try {
            $meilisearch->indexPrice($price);
        } catch (\Throwable $e) {
            $this->addFlash('error', 'Erreur Meilisearch : '.$e->getMessage());
        }

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

    #[Route('/purge', name: '_purge', methods: ['POST'])]
    public function purge(
        PriceAutomaticRepository $repository,
        EntityManagerInterface $em,
        MeilisearchService $meilisearch,
        #[Autowire(env: 'STRIPE_SK')] string $stripeSk = '',
    ): Response {
        $prices = $repository->findAll();
        $count = \count($prices);

        foreach ($prices as $price) {
            // Supprimer le produit Stripe si existe
            if ('' !== $stripeSk && null !== $price->getStripeId()) {
                try {
                    \Stripe\Stripe::setApiKey($stripeSk);
                    \Stripe\Product::update($price->getStripeId(), ['active' => false]);
                } catch (\Throwable) {
                    // Stripe desactivation best-effort
                }
            }

            // Supprimer de Meilisearch
            try {
                $meilisearch->removePrice($price->getId());
            } catch (\Throwable) {
                // Meilisearch cleanup best-effort
            }

            $em->remove($price);
        }

        $em->flush();

        $this->addFlash('success', $count.' tarif(s) purge(s) (DB + Stripe desactives + Meilisearch).');

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