<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

/** Platform catalog pathway (no owner_ref). */
class ClinicalPathway extends Model
{
    use SoftDeletes;

    protected $table = 'care_clinical_pathways';

    protected $fillable = [
        'uuid', 'code', 'name', 'description', 'match_rules',
        'is_active', 'sort_order', 'meta',
    ];

    protected function casts(): array
    {
        return [
            'match_rules' => 'array',
            'meta' => 'array',
            'is_active' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

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

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

    public function templates(): HasMany
    {
        return $this->hasMany(PathwayTemplate::class, 'pathway_id')->orderBy('sort_order');
    }

    public function patientPathways(): HasMany
    {
        return $this->hasMany(PatientPathway::class, 'pathway_id');
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    public static function findByCode(string $code): ?self
    {
        return static::query()->where('code', $code)->where('is_active', true)->first();
    }
}
