<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Console\Commands;

use PpPhp\Core\Platform\Console\AbstractCommand;
use PpPhp\Core\Platform\Console\ConsolePath;
use PpPhp\Core\Platform\Event\Verification\ListenerRegistryVerifier;

final class ListenersLockCommand extends AbstractCommand
{
    public function name(): string { return 'listeners:lock'; }
    public function description(): string { return 'Verify and lock listener registry subsystem.'; }

    public function handle(array $arguments = []): int
    {
        $base = ConsolePath::basePath();
        $result = (new ListenerRegistryVerifier())->verify($base);

        $payload = [
            'version' => 'R0100.5B',
            'status' => $result['ok'] ? 'locked' : 'failed',
            'lockedAt' => date('c'),
            'verification' => $result,
            'nextMilestone' => 'R0100.5C Lifecycle Events',
        ];

        $file = $base . '/storage/reports/r0100/r0100-listener-registry-lock.json';
        if (!is_dir(dirname($file))) {
            mkdir(dirname($file), 0775, true);
        }
        file_put_contents($file, json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

        $this->title('PPphp Listener Registry Lock');
        $this->line('Status: ' . ($result['ok'] ? 'LOCKED' : 'FAILED'));
        $this->line('File: storage/reports/r0100/r0100-listener-registry-lock.json');
        return $result['ok'] ? 0 : 1;
    }
}
