<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\Logger;

class WorkflowTimeoutJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }
    public function shouldRun(): bool { return true; }

    public function run(): array
    {
        $processed = 0;

        // Find workflow instances with timeout transitions
        $instances = $this->db->select(
            "SELECT wi.id, wi.workflow_definition_id, wi.current_state, wi.state_entered_at, wi.entity_type, wi.entity_id, wd.definition_json
             FROM workflow_instances wi
             JOIN workflow_definitions wd ON wd.id = wi.workflow_definition_id
             WHERE wi.is_completed = 0"
        );

        foreach ($instances as $inst) {
            $definition = json_decode($inst['definition_json'], true);
            if (!$definition) continue;

            $transitions = $definition['transitions'] ?? [];
            foreach ($transitions as $trans) {
                if (($trans['from'] ?? '') !== $inst['current_state']) continue;
                if (($trans['trigger'] ?? '') !== 'automatic') continue;

                // Check timeout guards
                foreach (($trans['guards'] ?? []) as $guard) {
                    if (($guard['type'] ?? '') !== 'timeout') continue;
                    $days = $guard['days'] ?? 0;
                    if ($days <= 0) continue;

                    $enteredAt = strtotime($inst['state_entered_at']);
                    $timeoutAt = $enteredAt + ($days * 86400);

                    if (time() >= $timeoutAt) {
                        // Execute timeout transition
                        $newState = $trans['to'];
                        $this->db->update('workflow_instances', [
                            'current_state'    => $newState,
                            'state_entered_at' => date('Y-m-d H:i:s'),
                            'is_completed'     => in_array(($definition['states'][$newState]['type'] ?? ''), ['terminal']) ? 1 : 0,
                            'completed_at'     => in_array(($definition['states'][$newState]['type'] ?? ''), ['terminal']) ? date('Y-m-d H:i:s') : null,
                            'updated_at'       => date('Y-m-d H:i:s'),
                        ], '`id` = ?', [(int) $inst['id']]);

                        $this->db->insert('workflow_transition_log', [
                            'workflow_instance_id' => (int) $inst['id'],
                            'from_state'           => $inst['current_state'],
                            'to_state'             => $newState,
                            'transition_name'      => $trans['name'] ?? 'timeout',
                            'trigger_type'         => 'timeout',
                            'created_at'           => date('Y-m-d H:i:s'),
                        ]);

                        Logger::info("Workflow timeout: instance #{$inst['id']} — {$inst['current_state']} → {$newState}");
                        $processed++;
                        break 2; // Only one transition per instance per run
                    }
                }
            }
        }

        return ['processed' => $processed];
    }
}