<?php

namespace App\Models;

use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class FacilityWorkflow extends Model
{
    use BelongsToOwner, SoftDeletes;

    protected $table = 'care_facility_workflows';

    protected $fillable = [
        'uuid', 'owner_ref', 'organization_id', 'branch_id', 'name',
        'template_key', 'category', 'is_active', 'settings',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'settings' => 'array',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (FacilityWorkflow $workflow) {
            if (! $workflow->uuid) {
                $workflow->uuid = (string) Str::uuid();
            }
        });
    }

    public function getRouteKeyName(): string
    {
        return 'uuid';
    }

    public function organization(): BelongsTo
    {
        return $this->belongsTo(Organization::class, 'organization_id');
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class, 'branch_id');
    }

    public function stages(): HasMany
    {
        return $this->hasMany(WorkflowStage::class, 'workflow_id')->orderBy('sort_order');
    }

    public function firstStage(): ?WorkflowStage
    {
        return $this->stages()->first();
    }

    public function stage(string $code): ?WorkflowStage
    {
        return $this->stages()->where('code', $code)->first();
    }
}
