<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Entity\SystemPrompt;
use App\Service\Admin\SystemPromptAdminService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[IsGranted('ROLE_SUPER_ADMIN')]
final class SystemPromptController extends AbstractController
{
    #[Route('/admin/system/prompt', name: 'admin_system_prompt', methods: ['GET', 'POST'])]
    public function index(
        Request $request,
        SystemPromptAdminService $svc
    ): Response {

        if ($request->isMethod('POST')) {
            try {
                $svc->create(
                    $request->request->get('content', ''),
                    $request->request->get('comment')
                );

                $this->addFlash('success', 'Neue Version gespeichert.');
                return $this->redirectToRoute('admin_system_prompt');

            } catch (\Throwable $e) {
                $this->addFlash('danger', $e->getMessage());
            }
        }

        return $this->render(
            'admin/system/prompt.html.twig',
            $svc->getIndexData()
        );
    }

    #[Route('/admin/system/prompt/{id}/activate', name: 'admin_system_prompt_activate', methods: ['POST'])]
    public function activate(
        SystemPrompt $prompt,
        SystemPromptAdminService $svc
    ): Response {

        try {
            $svc->activate($prompt);
            $this->addFlash('success', 'Version aktiviert.');
        } catch (\Throwable $e) {
            $this->addFlash('danger', $e->getMessage());
        }

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

    #[Route('/admin/system/prompt/{id}/delete', name: 'admin_system_prompt_delete', methods: ['POST'])]
    public function delete(
        SystemPrompt $prompt,
        SystemPromptAdminService $svc
    ): Response {

        try {
            $svc->delete($prompt);
            $this->addFlash('success', 'Version gelöscht.');
        } catch (\Throwable $e) {
            $this->addFlash('danger', $e->getMessage());
        }

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