<?php

namespace App\Workflows\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Step template within a workflow template
 */
class StepTemplate extends Model
{
    use HasFactory;

    protected $fillable = [
        'workflow_template_id',
        'position',
        'type',
        'system_key',
        'label',
        'form_definition',
        'validation',
        'data_bindings',
        'handler',
        'is_locked',
    ];

    protected $casts = [
        'form_definition' => 'array',
        'validation' => 'array',
        'data_bindings' => 'array',
        'is_locked' => 'boolean',
    ];

    /**
     * Create a new factory instance for the model.
     */
    protected static function newFactory()
    {
        return \Database\Factories\StepTemplateFactory::new();
    }

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

    public function isApprovalType(): bool
    {
        return $this->type === 'approval';
    }

    public function isInputType(): bool
    {
        return $this->type === 'input';
    }

    public function isAutoType(): bool
    {
        return $this->type === 'auto';
    }

    /**
     * Get the permission name for this step
     */
    public function getPermissionName(): string
    {
        // Use stable naming that persists across workflow versions
        $orgId = $this->workflowTemplate->org_id ?? 'global';
        $subjectType = class_basename($this->workflowTemplate->subject_type);

        // Prefer system_key for stability, fallback to position + label slug
        if ($this->system_key) {
            return "workflow_{$orgId}_{$subjectType}_{$this->system_key}";
        }

        // Create a stable slug from label for steps without system keys
        $labelSlug = str_replace([' ', '-', '_'], '_', strtolower($this->label));
        $labelSlug = preg_replace('/[^a-z0-9_]/', '', $labelSlug);
        $labelSlug = preg_replace('/_+/', '_', $labelSlug); // Replace multiple underscores with single

        return "workflow_{$orgId}_{$subjectType}_pos{$this->position}_{$labelSlug}";
    }

    /**
     * Get a human-readable permission label
     */
    public function getPermissionLabel(): string
    {
        $workflowName = $this->workflowTemplate->name ?? 'Unknown Workflow';

        return "{$workflowName} → {$this->label}";
    }
}
