<?php

declare(strict_types=1);

namespace Kylin\ElderlyCare\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Kylin\ElderlyCare\Services\HealthDataEncryptor;
use Kylin\ElderlyCare\Standards\HealthAbnormalDetector;
use Kylin\ElderlyCare\Traits\ElderlyCareAudit;

/**
 * 健康数据记录模型
 *
 * 依据《个人信息保护法》第二十八条，健康数据属于敏感个人信息，加密存储。
 * 依据 GB/T 35796-2017，健康档案离院后保留 >= 15 年。
 *
 * @property int    $id
 * @property int    $elderly_id      老人 ID
 * @property string $data_encrypted  加密的健康数据
 * @property string $abnormal_level  异常等级: normal/warning/critical
 * @property array  $abnormal_items  异常项
 * @property string $recorded_at     记录时间
 */
class HealthRecord extends Model
{
    use ElderlyCareAudit;

    protected $table = 'kylin_elderly_health_records';

    protected $fillable = [
        'elderly_id',
        'data_encrypted',
        'abnormal_level',
        'abnormal_items',
        'recorded_at',
    ];

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

    /**
     * 模型启动：保存前自动检测异常
     */
    protected static function booted(): void
    {
        static::saving(function (self $record) {
            $data = $record->getHealthData();
            $result = HealthAbnormalDetector::detect($data);

            $record->abnormal_level = $result['level'];
            $record->abnormal_items = $result['items'];
        });
    }

    /**
     * 设置健康数据（自动加密）
     */
    public function setHealthData(array $data): void
    {
        $this->data_encrypted = HealthDataEncryptor::encrypt($data);
    }

    /**
     * 获取健康数据（自动解密）
     */
    public function getHealthData(): array
    {
        if (empty($this->data_encrypted)) {
            return [];
        }
        return HealthDataEncryptor::decrypt($this->data_encrypted);
    }

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