<?php

declare(strict_types=1);

namespace PpPhp\Core\Designer\Contract;

final class DesignerStateVerifier
{
    public function verify(): array
    {
        $normalizer = new DesignerStateNormalizer();

        $state = $normalizer->ensurePage([], 'customers', 'list', 'list');
        $state['selection'] = DesignerSelectionModel::component('data_grid', 'columns', ['components', 0, 'props', 'columns', 0], [
            'field' => 'first_name',
        ])->toArray();

        $validation = DesignerJsonSchema::validate($state);
        $registry = DesignerComponentRegistry::defaults();

        $checks = [
            'schema' => $validation['ok'] === true,
            'normalization' => isset($state['pages']['customers']['list']['pages']['list']),
            'pageContract' => isset($state['pages']['customers']['list']['pages']['list']['resources']),
            'selection' => ($state['selection']['componentId'] ?? '') === 'data_grid',
            'registry' => $registry->has('table-grid') && $registry->has('button'),
            'resources' => isset($state['resources']['icons'], $state['resources']['css'], $state['resources']['js']),
        ];

        $issues = [];
        foreach ($checks as $check => $ok) {
            if (!$ok) {
                $issues[] = [
                    'check' => $check,
                    'message' => 'Designer state verification failed: ' . $check,
                ];
            }
        }

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'checks' => count($checks),
                'passed' => count(array_filter($checks)),
                'failed' => count($checks) - count(array_filter($checks)),
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
            'state' => $state,
        ];
    }
}
