<?php

namespace App\Models;

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

class SpecialtyClinicalRecord extends Model
{
    use BelongsToOwner, SoftDeletes;

    public const STATUS_DRAFT = 'draft';

    public const STATUS_ACTIVE = 'active';

    public const STATUS_COMPLETED = 'completed';

    protected $table = 'care_specialty_clinical_records';

    protected $fillable = [
        'uuid', 'owner_ref', 'organization_id', 'branch_id', 'visit_id', 'patient_id',
        'consultation_id', 'module_key', 'record_type', 'status', 'stage_code',
        'payload', 'alerts', 'recorded_by', 'recorded_at',
    ];

    protected function casts(): array
    {
        return [
            'payload' => 'array',
            'alerts' => 'array',
            'recorded_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (SpecialtyClinicalRecord $record) {
            if (! $record->uuid) {
                $record->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 visit(): BelongsTo
    {
        return $this->belongsTo(Visit::class, 'visit_id');
    }

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

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

    /**
     * @return list<array{code: string, severity: string, message: string}>
     */
    public function activeAlerts(): array
    {
        $alerts = $this->alerts ?? [];

        return is_array($alerts) ? array_values($alerts) : [];
    }
}
