<?php

namespace App\Workflows\Models;

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

/**
 * Workflow template - versioned, immutable when published
 */
class WorkflowTemplate extends Model
{
    use BelongsToOrg, HasFactory;

    protected $fillable = [
        'org_id',
        'name',
        'subject_type',
        'status',
        'version',
        'is_active',
        'published_at',
    ];

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

    protected $casts = [
        'published_at' => 'datetime',
        'is_active' => 'boolean',
    ];

    public function stepTemplates(): HasMany
    {
        return $this->hasMany(StepTemplate::class)->orderBy('position');
    }

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

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

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

    /**
     * Validate that all required system keys are present in steps
     */
    public function validateRequiredSystemKeys(): array
    {
        $requiredKeys = config('workflows.required_steps')[$this->subject_type] ?? [];
        $presentKeys = $this->stepTemplates()->whereNotNull('system_key')->pluck('system_key')->unique()->toArray();

        return array_diff($requiredKeys, $presentKeys);
    }

    /**
     * Check if workflow template has all required system keys
     */
    public function hasAllRequiredSystemKeys(): bool
    {
        return empty($this->validateRequiredSystemKeys());
    }
}
