<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Entity\IngestProfile;
use App\Service\Admin\IngestProfileAdminService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/admin/ingest-profiles')]
final class IngestProfileController extends AbstractController
{
    #[Route('/', name: 'admin_ingest_profile_list')]
    public function list(IngestProfileAdminService $svc): Response
    {
        $data = $svc->listData();

        return $this->render('admin/ingest_profile/list.html.twig', $data);
    }

    #[Route('/create', name: 'admin_ingest_profile_create', methods: ['GET', 'POST'])]
    public function create(Request $request, IngestProfileAdminService $svc): Response
    {
        if ($request->isMethod('POST')) {
            try {
                $svc->create([
                    'chunk_size' => $request->request->get('chunk_size'),
                    'chunk_overlap' => $request->request->get('chunk_overlap'),
                    'embedding_model' => $request->request->get('embedding_model'),
                    'embedding_dimension' => $request->request->get('embedding_dimension'),
                    'scoring_version' => $request->request->get('scoring_version'),
                ]);

                $this->addFlash('success', 'Ingest-Profil wurde erstellt.');
                return $this->redirectToRoute('admin_ingest_profile_list');
            } catch (\Throwable $e) {
                $this->addFlash('danger', $e->getMessage());
                // fallthrough -> render form again
            }
        }

        return $this->render('admin/ingest_profile/create.html.twig');
    }

    #[Route('/activate/{id}', name: 'admin_ingest_profile_activate', methods: ['POST'])]
    public function activate(
        IngestProfile $profile,
        IngestProfileAdminService $svc
    ): Response {
        try {
            $svc->activate($profile);
            $this->addFlash('success', 'Ingest-Profil wurde aktiviert.');
        } catch (\Throwable $e) {
            $this->addFlash('danger', $e->getMessage());
        }

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

    #[Route('/remove/{id}', name: 'admin_ingest_profile_remove', methods: ['POST', 'GET'])]
    public function remove(string $id, IngestProfileAdminService $svc): Response
    {
        try {
            $svc->remove($id);
            $this->addFlash('success', 'Ingest-Profil wurde entfernt.');
        } catch (\Throwable $e) {
            $this->addFlash('danger', $e->getMessage());
        }

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