<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Auth;

final class DesignerAuthRuntime
{
    private array $operations = [];

    public function createPage(string $pageType): array
    {
        $page = DesignerAuthPageDefinition::create($pageType)->toPage();
        $this->record('createPage', ['pageType' => $pageType]);
        return $page;
    }

    public function createSuite(): array
    {
        $types = ['login', 'register', 'forgot_password', 'reset_password', 'change_password', 'profile', 'user_info', 'access_denied'];
        $pages = [];

        foreach ($types as $type) {
            $pages[$type] = $this->createPage($type);
        }

        $this->record('createSuite', ['pages' => count($pages)]);
        return $pages;
    }

    public function render(array $page): string
    {
        return (new DesignerAuthRenderer())->render($page);
    }

    public function validate(array $page): array
    {
        $component = (array) (($page['components'][0] ?? [])['props'] ?? []);
        $fields = (array) ($component['fields'] ?? []);
        $actions = (array) ($component['actions'] ?? []);

        return [
            'ok' => (($page['pageType'] ?? '') !== '') && ($actions !== [] || ($page['pageType'] ?? '') === 'user_info'),
            'pageType' => $page['pageType'] ?? '',
            'fields' => count($fields),
            'actions' => count($actions),
            'csrf' => (bool) ($component['security']['csrf'] ?? false),
        ];
    }

    public function operations(): array { return $this->operations; }

    public function stats(array $suite = []): array
    {
        return [
            'operations' => count($this->operations),
            'pages' => count($suite),
            'authRequired' => count(array_filter($suite, static fn (array $page): bool => (bool) (($page['components'][0]['props']['security']['authRequired'] ?? false)))),
            'guestOnly' => count(array_filter($suite, static fn (array $page): bool => (bool) (($page['components'][0]['props']['security']['guestOnly'] ?? false)))),
        ];
    }

    private function record(string $operation, array $payload): void
    {
        $this->operations[] = ['operation' => $operation, 'payload' => $payload, 'createdAt' => date('c')];
    }
}
