<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
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;

/**
 * Platform catalog row (no owner_ref). System templates in v1 always have null organization_id.
 */
class AssessmentTemplate extends Model
{
    use SoftDeletes;

    public const CATEGORY_UNIVERSAL = 'universal';

    public const CATEGORY_DISEASE = 'disease';

    public const CATEGORY_OUTCOME = 'outcome';

    public const CATEGORY_SCREENING = 'screening';

    protected $table = 'care_assessment_templates';

    protected $fillable = [
        'uuid', 'organization_id', 'code', 'name', 'category', 'description',
        'version', 'is_current', 'scoring_strategy', 'meta', 'is_active',
    ];

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

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

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

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

    public function questions(): HasMany
    {
        return $this->hasMany(AssessmentQuestion::class, 'template_id')->orderBy('sort_order');
    }

    public function assessments(): HasMany
    {
        return $this->hasMany(Assessment::class, 'template_id');
    }

    public function scopeSystem(Builder $query): Builder
    {
        return $query->whereNull($this->getTable().'.organization_id');
    }

    public function scopeCurrent(Builder $query): Builder
    {
        return $query->where($this->getTable().'.is_current', true)
            ->where($this->getTable().'.is_active', true);
    }

    /**
     * Resolve the current system template for a stable code (e.g. nihss, universal_intake).
     */
    public static function currentSystemByCode(string $code): ?self
    {
        return static::query()
            ->system()
            ->current()
            ->where('code', $code)
            ->first();
    }
}
