<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\DragDrop\Validation;

use PpPhp\Core\Designer\DragDrop\DesignerDragDropRuntime;
use PpPhp\Core\Designer\DragDrop\DesignerDragPayload;
use PpPhp\Core\Designer\DragDrop\DesignerDropTarget;
use PpPhp\Core\Designer\Templates\MinimalListPageTemplate;

final class DesignerDragDropVerifier
{
    public function verify(): array
    {
        $runtime = new DesignerDragDropRuntime();
        $page = (new MinimalListPageTemplate())->make('customers');

        $initial = count($page['components'] ?? []);

        $insert = $runtime->insert($page, DesignerDragPayload::toolbox('button'), DesignerDropTarget::page());
        $page = $insert->page();
        $insertedId = $insert->toArray()['componentId'] ?? '';

        $move = $runtime->move($page, $insertedId, DesignerDropTarget::page(1));
        $page = $move->page();

        $duplicate = $runtime->duplicate($page, $insertedId, DesignerDropTarget::page());
        $page = $duplicate->page();

        $runtime->copy($page['components'][0]);
        $paste = $runtime->paste($page, DesignerDropTarget::page());
        $pageAfterPaste = $paste->page();

        $undo = $runtime->undo($pageAfterPaste);
        $redo = $runtime->redo($undo);

        $stats = $runtime->stats();

        $checks = [
            'insert' => $insert->isSuccess() && count($page['components'] ?? []) >= $initial + 2,
            'move' => $move->isSuccess(),
            'duplicate' => $duplicate->isSuccess() && str_contains((string)($duplicate->toArray()['componentId'] ?? ''), '_copy_1'),
            'clipboardPaste' => $paste->isSuccess(),
            'undo' => count($undo['components'] ?? []) < count($pageAfterPaste['components'] ?? []),
            'redo' => count($redo['components'] ?? []) === count($pageAfterPaste['components'] ?? []),
            'operations' => ($stats['operations'] ?? 0) >= 4,
            'history' => isset($stats['history']['undo'], $stats['history']['redo']),
        ];

        $issues = [];
        foreach ($checks as $check => $ok) {
            if (!$ok) {
                $issues[] = ['check' => $check, 'message' => 'Designer drag/drop 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)),
                'operations' => $stats['operations'] ?? 0,
                'insertions' => $stats['insertions'] ?? 0,
                'moves' => $stats['moves'] ?? 0,
                'duplicates' => $stats['duplicates'] ?? 0,
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
            'operations' => $runtime->operations(),
        ];
    }
}
