<?php

declare(strict_types=1);

namespace Kylin\ElderlyCare\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Kylin\ElderlyCare\Standards\CareLevelCalculator;
use Kylin\ElderlyCare\Traits\ElderlyCareAudit;

/**
 * 护理评估记录模型
 *
 * 依据 GB/T 42195-2022《老年人能力评估规范》。
 * 评估指标：日常生活活动、精神状态、感知觉与沟通、社会参与。
 * 评估周期：6 个月（180 天）。
 *
 * @property int    $id
 * @property int    $elderly_id        老人 ID
 * @property int    $daily_living       日常生活活动得分
 * @property int    $mental_state       精神状态得分
 * @property int    $perception         感知觉与沟通得分
 * @property int    $social_participation 社会参与得分
 * @property int    $total_score        总分
 * @property int    $care_level         护理等级 0-3
 * @property string $assessor           评估人
 * @property string $assessed_at        评估时间
 */
class CareAssessment extends Model
{
    use ElderlyCareAudit;

    protected $table = 'kylin_elderly_assessments';

    protected $fillable = [
        'elderly_id',
        'daily_living',
        'mental_state',
        'perception',
        'social_participation',
        'total_score',
        'care_level',
        'assessor',
        'assessed_at',
    ];

    protected function casts(): array
    {
        return [
            'daily_living' => 'integer',
            'mental_state' => 'integer',
            'perception' => 'integer',
            'social_participation' => 'integer',
            'total_score' => 'integer',
            'care_level' => 'integer',
            'assessed_at' => 'datetime',
        ];
    }

    /**
     * 模型启动：保存前自动计算总分和护理等级
     */
    protected static function booted(): void
    {
        static::saving(function (self $assessment) {
            $assessment->total_score = $assessment->daily_living
                + $assessment->mental_state
                + $assessment->perception
                + $assessment->social_participation;

            $assessment->care_level = CareLevelCalculator::calculate($assessment->total_score);
        });
    }

    public function elderly(): BelongsTo
    {
        return $this->belongsTo(ElderlyProfile::class, 'elderly_id');
    }

    /**
     * 获取护理等级标签
     */
    public function getCareLevelLabelAttribute(): string
    {
        return CareLevelCalculator::label($this->care_level);
    }
}
