<?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 PatientPathway extends Model
{
    use BelongsToOwner, SoftDeletes;

    public const STATUS_ACTIVE = 'active';

    public const STATUS_RESOLVED = 'resolved';

    public const STATUS_INACTIVE = 'inactive';

    protected $table = 'care_patient_pathways';

    protected $fillable = [
        'uuid', 'owner_ref', 'organization_id', 'patient_id', 'pathway_id',
        'status', 'activated_at', 'activated_by', 'activation_consultation_id',
        'activation_diagnosis_text', 'resolved_at', 'notes',
    ];

    protected function casts(): array
    {
        return [
            'activated_at' => 'datetime',
            'resolved_at' => 'datetime',
        ];
    }

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

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

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

    public function patient(): BelongsTo
    {
        return $this->belongsTo(Patient::class, 'patient_id');
    }

    public function pathway(): BelongsTo
    {
        return $this->belongsTo(ClinicalPathway::class, 'pathway_id');
    }

    public function activationConsultation(): BelongsTo
    {
        return $this->belongsTo(Consultation::class, 'activation_consultation_id');
    }

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

    public function isActive(): bool
    {
        return $this->status === self::STATUS_ACTIVE;
    }
}
