<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Form\Validation;

use PpPhp\Core\Designer\Form\DesignerFormRuntime;

final class DesignerFormVerifier
{
    public function verify(): array
    {
        $runtime = new DesignerFormRuntime();

        $create = $runtime->create('customer_add_form', 'add', 'Add Customer', 'two_column');
        $withField = $runtime->addField($create, ['name' => 'first_name', 'type' => 'text', 'label' => 'First Name']);
        $withField = $runtime->addField($withField, ['name' => 'email', 'type' => 'email', 'label' => 'Email']);
        $removed = $runtime->removeField($withField, 'first_name');

        $page = $runtime->pageFor('customers', 'edit', [
            ['name' => 'first_name', 'type' => 'text', 'label' => 'First Name'],
            ['name' => 'email', 'type' => 'email', 'label' => 'Email'],
            ['name' => 'status', 'type' => 'select', 'label' => 'Status', 'props' => ['options' => ['active', 'inactive']]],
        ]);

        $validation = $runtime->validate($page['components'][1]);
        $stats = $runtime->stats();

        $checks = [
            'create' => ($create['type'] ?? '') === 'form' && (($create['props']['mode'] ?? '') === 'add'),
            'addField' => (($withField['props']['fieldCount'] ?? 0) === 2),
            'removeField' => (($removed['props']['fieldCount'] ?? 0) === 1),
            'pageFor' => ($page['pageType'] ?? '') === 'edit' && count($page['components'] ?? []) === 2,
            'validation' => ($validation['ok'] ?? false) === true && ($validation['fieldCount'] ?? 0) === 3,
            'layout' => (($page['components'][1]['props']['layout']['columns'] ?? 0) === 2),
            'operations' => ($stats['operations'] ?? 0) >= 5,
        ];

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

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