<?php

declare(strict_types=1);

namespace App\Service\Admin;

use App\Entity\SystemPrompt;
use App\Repository\SystemPromptRepository;
use Doctrine\ORM\EntityManagerInterface;

final readonly class SystemPromptAdminService
{
    public function __construct(
        private SystemPromptRepository $repo,
        private EntityManagerInterface $em,
    ) {}

    /**
     * @return array{
     *   active:?SystemPrompt,
     *   all:array
     * }
     */
    public function getIndexData(): array
    {
        return [
            'active' => $this->repo->findActive(),
            'all'    => $this->repo->findBy([], ['version' => 'DESC']),
        ];
    }

    public function create(string $content, ?string $comment): SystemPrompt
    {
        $content = trim($content);

        if ($content === '') {
            throw new \InvalidArgumentException('System Prompt darf nicht leer sein.');
        }

        // aktive Version deaktivieren
        $active = $this->repo->findActive();
        if ($active instanceof SystemPrompt) {
            $active->deactivate();
        }

        $new = new SystemPrompt(
            version: $this->repo->getNextVersion(),
            content: $content,
            comment: $comment ? trim($comment) : null,
            active: true
        );

        $this->em->persist($new);
        $this->em->flush();

        return $new;
    }

    public function activate(SystemPrompt $prompt): void
    {
        // alle aktiven deaktivieren (sicherheitsrobust)
        foreach ($this->repo->findBy(['active' => true]) as $p) {
            $p->deactivate();
        }

        $prompt->activate();

        $this->em->flush();
    }

    public function delete(SystemPrompt $prompt): void
    {
        if ($prompt->isActive()) {
            throw new \RuntimeException('Aktive Version kann nicht gelöscht werden.');
        }

        $this->em->remove($prompt);
        $this->em->flush();
    }
}