<?php
declare(strict_types=1);

namespace App\Modules\Workflow\Models;

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

class WorkflowInstance extends Model
{
    protected static string $table = 'workflow_instances';
    protected static bool $softDelete = false;
    protected static bool $timestamps = true;
    protected static array $fillable = [
        'workflow_definition_id', 'workflow_code', 'entity_type', 'entity_id',
        'current_state', 'state_entered_at', 'state_data_json',
        'is_completed', 'completed_at',
    ];

    public function getStateData(): array
    {
        return json_decode($this->state_data_json ?? '{}', true) ?? [];
    }

    public function getDefinition(): ?WorkflowDefinition
    {
        return WorkflowDefinition::find((int) $this->workflow_definition_id);
    }

    public static function findForEntity(string $entityType, int $entityId, ?string $workflowCode = null): ?static
    {
        $db = App::getInstance()->db();
        $sql = "SELECT * FROM workflow_instances WHERE entity_type = ? AND entity_id = ? AND is_completed = 0";
        $params = [$entityType, $entityId];

        if ($workflowCode !== null) {
            $sql .= " AND workflow_code = ?";
            $params[] = $workflowCode;
        }

        $sql .= " ORDER BY created_at DESC LIMIT 1";
        $row = $db->selectOne($sql, $params);
        if (!$row) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }

    public static function allForEntity(string $entityType, int $entityId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT wi.*, wd.name_ar as definition_name_ar FROM workflow_instances wi JOIN workflow_definitions wd ON wd.id = wi.workflow_definition_id WHERE wi.entity_type = ? AND wi.entity_id = ? ORDER BY wi.created_at DESC",
            [$entityType, $entityId]
        );
    }

    public static function getActiveByState(string $workflowCode, string $state): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM workflow_instances WHERE workflow_code = ? AND current_state = ? AND is_completed = 0",
            [$workflowCode, $state]
        );
    }

    public static function getTimedOut(string $workflowCode, string $state, int $timeoutDays): array
    {
        $db = App::getInstance()->db();
        $cutoff = date('Y-m-d H:i:s', time() - ($timeoutDays * 86400));
        return $db->select(
            "SELECT * FROM workflow_instances WHERE workflow_code = ? AND current_state = ? AND is_completed = 0 AND state_entered_at <= ?",
            [$workflowCode, $state, $cutoff]
        );
    }
}