<?php

namespace App\Workflows\Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Step instance for audit trail
 */
class StepInstance extends Model
{
    use HasFactory;

    protected $fillable = [
        'workflow_instance_id',
        'step_template_id',
        'status',
        'acted_by',
        'acted_at',
        'data',
        'note',
        'step_template_snapshot',
    ];

    protected $casts = [
        'data' => 'array',
        'step_template_snapshot' => 'array',
        'acted_at' => 'datetime',
    ];

    public function workflowInstance(): BelongsTo
    {
        return $this->belongsTo(WorkflowInstance::class);
    }

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

    public function actor(): BelongsTo
    {
        return $this->belongsTo(User::class, 'acted_by');
    }

    public function isPending(): bool
    {
        return $this->status === 'pending';
    }

    public function isApproved(): bool
    {
        return $this->status === 'approved';
    }

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

    public function isSkipped(): bool
    {
        return $this->status === 'skipped';
    }

    /**
     * Get the step label from snapshot
     */
    public function getLabel(): string
    {
        return $this->step_template_snapshot['label'] ?? 'Unknown Step';
    }

    /**
     * Get the step system key from snapshot
     */
    public function getSystemKey(): ?string
    {
        return $this->step_template_snapshot['system_key'] ?? null;
    }
}
