<?php

declare(strict_types=1);

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\Logging\DefaultLogger;
use App\Framework\Logging\Handlers\ConsoleHandler;
use App\Framework\Scheduler\Services\SchedulerService;
use App\Framework\Worker\Every;
use App\Framework\Worker\Schedule;
use App\Framework\Worker\ScheduleDiscoveryService;
use App\Framework\Discovery\Results\DiscoveryRegistry;
use App\Framework\Discovery\Results\AttributeRegistry;

// Test job class
#[Schedule(at: new Every(minutes: 5))]
final class DebugScheduledJob
{
    public function handle(): array
    {
        return ['status' => 'success', 'executed_at' => time()];
    }
}

// Setup logger
$logger = new DefaultLogger(handlers: [new ConsoleHandler()]);

// Setup scheduler
$schedulerService = new SchedulerService($logger);

// Setup discovery registry with attribute registry
$attributeRegistry = new AttributeRegistry();
$attributeRegistry->register(Schedule::class, DebugScheduledJob::class);

$discoveryRegistry = new DiscoveryRegistry($attributeRegistry);

// Create discovery service
$scheduleDiscovery = new ScheduleDiscoveryService(
    $discoveryRegistry,
    $schedulerService
);

echo "=== Testing ScheduleDiscoveryService ===\n\n";

// Discover and register
$registered = $scheduleDiscovery->discoverAndRegister();
echo "Registered: {$registered} tasks\n\n";

// Get scheduled tasks
$scheduledTasks = $scheduleDiscovery->getScheduledTasks();
echo "Scheduled tasks count: " . count($scheduledTasks) . "\n\n";

foreach ($scheduledTasks as $task) {
    echo "Task ID: {$task->taskId}\n";
    echo "Next execution: {$task->nextExecution->format('Y-m-d H:i:s')}\n";
    echo "---\n";
}

// Execute a task
if (count($scheduledTasks) > 0) {
    $task = $scheduledTasks[0];
    echo "\nExecuting task: {$task->taskId}\n";

    $result = $schedulerService->executeTask($task);

    echo "Success: " . ($result->success ? 'Yes' : 'No') . "\n";
    echo "Result: " . json_encode($result->result, JSON_PRETTY_PRINT) . "\n";

    if ($result->error) {
        echo "Error: {$result->error}\n";
    }
}

echo "\n=== Test completed ===\n";
