<?php

namespace App\Workflows\Models;

use App\Traits\BelongsToOrg;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;

/**
 * Runtime workflow instance per subject (e.g., Order)
 */
class WorkflowInstance extends Model
{
    use BelongsToOrg, HasFactory;

    protected $fillable = [
        'workflow_template_id',
        'org_id',
        'subject_type',
        'subject_id',
        'state',
    ];

    public function template(): BelongsTo
    {
        return $this->belongsTo(WorkflowTemplate::class, 'workflow_template_id');
    }

    public function stepInstances(): HasMany
    {
        return $this->hasMany(StepInstance::class);
    }

    public function subject(): MorphTo
    {
        return $this->morphTo();
    }

    /**
     * Get the current (first pending) step
     */
    public function currentStep(): ?StepInstance
    {
        return $this->stepInstances()
            ->where('status', 'pending')
            ->orderBy('id')
            ->first();
    }

    public function isCompleted(): bool
    {
        return $this->state === 'completed';
    }

    public function isRunning(): bool
    {
        return $this->state === 'running';
    }

    public function isRejected(): bool
    {
        return $this->state === 'rejected';
    }

    public function isCanceled(): bool
    {
        return $this->state === 'canceled';
    }
}
