<?php

declare(strict_types=1);

trait MyronContentLifecycleTrait
{
    /**
     * @var list<string>
     */
    private array $starterDefaultTemplateIds = [
        'template.home.default.v1',
        'template.about.default.v1',
    ];

    /**
     * @return array<string, int>
     */
    public function resetToBaselineSeed(): array
    {
        $counts = [
            'page_versions' => (int) $this->pdo->query('SELECT COUNT(*) FROM page_versions')->fetchColumn(),
            'pages' => (int) $this->pdo->query('SELECT COUNT(*) FROM pages')->fetchColumn(),
            'page_template_versions' => (int) $this->pdo->query('SELECT COUNT(*) FROM page_template_versions')->fetchColumn(),
            'page_templates' => (int) $this->pdo->query('SELECT COUNT(*) FROM page_templates')->fetchColumn(),
            'menu_items' => (int) $this->pdo->query('SELECT COUNT(*) FROM menu_items')->fetchColumn(),
            'menus' => (int) $this->pdo->query('SELECT COUNT(*) FROM menus')->fetchColumn(),
            'bundle_seed_records' => (int) $this->pdo->query('SELECT COUNT(*) FROM bundle_seed_records')->fetchColumn(),
        ];

        $this->pdo->beginTransaction();

        try {
            $this->pdo->exec('UPDATE menu_placements SET menu_id = NULL, updated_at = ' . $this->pdo->quote(myronNow()));
            $this->pdo->exec('DELETE FROM menu_items');
            $this->pdo->exec('DELETE FROM menus');
            $this->pdo->exec('DELETE FROM page_versions');
            $this->pdo->exec('DELETE FROM pages');
            $this->pdo->exec('DELETE FROM page_template_versions');
            $this->pdo->exec('DELETE FROM page_templates');
            $this->pdo->exec('DELETE FROM bundle_seed_records');

            if ($this->pdo->inTransaction()) {
                $this->pdo->commit();
            }
        } catch (Throwable $exception) {
            if ($this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }

            throw $exception;
        }

        $this->ensureSeedData();

        return $counts;
    }

    public function ensureSeedData(): void
    {
        if ($this->hasConfiguredOnboardingState()) {
            $this->ensureSeedMenus();
            return;
        }

        $templateCount = (int) $this->pdo->query('SELECT COUNT(*) FROM page_templates')->fetchColumn();
        if ($templateCount === 0) {
            $this->seedDefaultTemplate();
        }

        $pageCount = (int) $this->pdo->query('SELECT COUNT(*) FROM pages')->fetchColumn();
        if ($pageCount === 0 && !$this->seedStarterDefaultPages()) {
            $this->seedLegacyDefaultPages();
        }

        $this->ensureSeedMenus();
    }

    private function seedStarterDefaultPages(): bool
    {
        if (!class_exists('MyronTemplateDefinitionRepository') || !class_exists('MyronTemplateInstantiationService')) {
            return false;
        }

        if (function_exists('myronEnsureDefinitionsRuntimeSeeded')) {
            myronEnsureDefinitionsRuntimeSeeded();
        }

        $templateRepository = new MyronTemplateDefinitionRepository($this->pdo);
        $instantiator = new MyronTemplateInstantiationService($this->pdo, $this);
        $seededPages = 0;

        foreach ($this->starterDefaultTemplateIds as $templateId) {
            $definition = $templateRepository->findTemplateById($templateId);
            if (!is_array($definition)) {
                return false;
            }

            $runtimeTemplate = $instantiator->instantiateTemplate($definition);
            $runtimePage = $instantiator->instantiatePage($definition, $runtimeTemplate);
            if (is_array($runtimePage)) {
                $seededPages++;
            }
        }

        return $seededPages === count($this->starterDefaultTemplateIds);
    }

    private function seedLegacyDefaultPages(): void
    {
        $template = $this->findTemplateByKey('basic-page');
        if ($template === null) {
            throw new RuntimeException('Default page template was not created.');
        }

        $homePageId = $this->createPage(
            (string) $template['id'],
            'Home',
            'home',
            null,
            'MyronCMS',
            'A calm, governed CMS shell with DB-backed publishing.',
            [
                'eyebrow' => 'Home page',
                'headline' => 'Build pages from a governed design system.',
                'intro' => 'MyronCMS now renders published page state from the database while preserving the boundaries between templates, pages, and page versions.',
                'body' => "This first slice proves the CMS can own page identity, route ownership, and publish state without collapsing into a freeform editor.\n\nThe broader domain model is still preserved for templates, assets, approvals, and future collaboration layers.",
                'ctaLabel' => 'See the sub-page',
                'ctaHref' => '/about',
            ],
            true
        );

        $this->createPage(
            (string) $template['id'],
            'About',
            'about',
            null,
            'About MyronCMS',
            'Why the domain model matters before feature sprawl.',
            [
                'eyebrow' => 'About page',
                'headline' => 'A narrow page slice with a durable model underneath.',
                'intro' => 'MyronCMS is proving page publishing with the smallest useful DB-backed flow, while still honoring the broader entity architecture.',
                'body' => "Pages remain created from templates.\n\nPublished content is versioned separately from page identity.\n\nThat means the first content slice is useful now without painting the CMS into a corner later.",
                'ctaLabel' => 'Back to home',
                'ctaHref' => '/',
            ],
            true
        );

        if ($homePageId === '') {
            throw new RuntimeException('Failed to create seeded home page.');
        }
    }

    private function hasConfiguredOnboardingState(): bool
    {
        $statement = $this->pdo->query(
            "SELECT setup_status
             FROM onboarding_state
             WHERE id = 1
             LIMIT 1"
        );
        $status = $statement ? $statement->fetchColumn() : false;

        return is_string($status) && trim($status) === 'configured';
    }
}
