<?php
declare(strict_types=1);

namespace App\Modules\Workflow\Models;

use App\Core\Model;
use App\Core\App;

class WorkflowDefinition extends Model
{
    protected static string $table = 'workflow_definitions';
    protected static bool $softDelete = false;
    protected static bool $timestamps = true;
    protected static array $fillable = [
        'workflow_code', 'name_ar', 'name_en', 'description_ar',
        'definition_json', 'version', 'is_active',
    ];

    public function getDefinition(): array
    {
        return json_decode($this->definition_json ?? '{"states":{},"transitions":[]}', true) ?? ['states' => [], 'transitions' => []];
    }

    public function getStates(): array
    {
        $def = $this->getDefinition();
        return $def['states'] ?? [];
    }

    public function getTransitions(): array
    {
        $def = $this->getDefinition();
        return $def['transitions'] ?? [];
    }

    public function getTransitionsFrom(string $state): array
    {
        $transitions = $this->getTransitions();
        return array_filter($transitions, fn($t) => ($t['from'] ?? '') === $state);
    }

    public function getInitialState(): ?string
    {
        foreach ($this->getStates() as $key => $state) {
            if (($state['type'] ?? '') === 'initial') {
                return $key;
            }
        }
        $states = $this->getStates();
        return !empty($states) ? array_key_first($states) : null;
    }

    public function findTransition(string $name): ?array
    {
        foreach ($this->getTransitions() as $t) {
            if (($t['name'] ?? '') === $name) {
                return $t;
            }
        }
        return null;
    }

    public static function findByCode(string $code): ?static
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne("SELECT * FROM workflow_definitions WHERE workflow_code = ? AND is_active = 1", [$code]);
        if (!$row) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }

    public static function allActive(): array
    {
        $db = App::getInstance()->db();
        return $db->select("SELECT * FROM workflow_definitions WHERE is_active = 1 ORDER BY name_ar");
    }
}