<?php

/**
 * 智慧养老数据库迁移
 *
 * 依据《养老机构管理办法》第十七条，建立老年人健康档案。
 * 依据《个人信息保护法》第二十八条，健康数据加密存储。
 * 依据 GB/T 42195-2022，老年人能力评估四级分类。
 * 依据 GB/T 35796-2017，健康档案离院后保留 >= 15 年。
 */

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // 1. 老人档案表
        Schema::create('kylin_elderly_profiles', function (Blueprint $table) {
            $table->id();
            $table->string('name', 100)->comment('姓名（加密存储）');
            $table->text('id_card_encrypted')->nullable()->comment('身份证号（AES 加密）');
            $table->string('gender', 10)->nullable()->comment('性别');
            $table->date('birth_date')->nullable()->comment('出生日期');
            $table->string('phone', 255)->nullable()->comment('联系电话（加密存储）');
            $table->string('emergency_contact', 255)->nullable()->comment('紧急联系人（加密存储）');
            $table->string('emergency_phone', 255)->nullable()->comment('紧急联系电话（加密存储）');
            $table->tinyInteger('care_level')->default(0)->comment('护理等级 0=完好 1=轻度 2=中度 3=重度');
            $table->date('admission_date')->nullable()->comment('入院日期');
            $table->date('discharge_date')->nullable()->comment('离院日期');
            $table->string('status', 20)->default('active')->comment('状态: active/discharged');
            $table->timestamps();
            $table->softDeletes();

            $table->index('care_level');
            $table->index('status');
        });

        // 2. 护理评估记录表
        Schema::create('kylin_elderly_assessments', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('elderly_id')->comment('老人 ID');
            $table->integer('daily_living')->default(0)->comment('日常生活活动得分');
            $table->integer('mental_state')->default(0)->comment('精神状态得分');
            $table->integer('perception')->default(0)->comment('感知觉与沟通得分');
            $table->integer('social_participation')->default(0)->comment('社会参与得分');
            $table->integer('total_score')->default(0)->comment('总分');
            $table->tinyInteger('care_level')->default(0)->comment('护理等级 0-3');
            $table->string('assessor', 64)->nullable()->comment('评估人');
            $table->timestamp('assessed_at')->comment('评估时间');
            $table->timestamps();

            $table->foreign('elderly_id')->references('id')->on('kylin_elderly_profiles')->cascadeOnDelete();
            $table->index(['elderly_id', 'assessed_at']);
            $table->index('care_level');
        });

        // 3. 健康数据记录表
        Schema::create('kylin_elderly_health_records', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('elderly_id')->comment('老人 ID');
            $table->text('data_encrypted')->comment('加密的健康数据（AES）');
            $table->string('abnormal_level', 20)->default('normal')->comment('异常等级: normal/warning/critical');
            $table->json('abnormal_items')->nullable()->comment('异常项（JSON）');
            $table->timestamp('recorded_at')->comment('记录时间');
            $table->timestamps();

            $table->foreign('elderly_id')->references('id')->on('kylin_elderly_profiles')->cascadeOnDelete();
            $table->index(['elderly_id', 'recorded_at']);
            $table->index('abnormal_level');
        });

        // 4. 用药记录表
        Schema::create('kylin_elderly_medication_records', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('elderly_id')->comment('老人 ID');
            $table->string('medication', 100)->comment('药品名称');
            $table->string('dosage', 50)->nullable()->comment('剂量');
            $table->timestamp('scheduled_at')->comment('计划用药时间');
            $table->timestamp('administered_at')->nullable()->comment('实际用药时间');
            $table->boolean('is_missed')->default(false)->comment('是否漏服');
            $table->string('administrator', 64)->nullable()->comment('给药人');
            $table->text('remark')->nullable()->comment('备注');
            $table->timestamps();

            $table->foreign('elderly_id')->references('id')->on('kylin_elderly_profiles')->cascadeOnDelete();
            $table->index(['elderly_id', 'scheduled_at']);
            $table->index('is_missed');
        });

        // 5. 紧急呼叫记录表
        Schema::create('kylin_elderly_emergency_calls', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('elderly_id')->comment('老人 ID');
            $table->string('call_type', 20)->default('manual')->comment('呼叫类型: manual/auto/device');
            $table->string('location', 200)->nullable()->comment('呼叫位置');
            $table->timestamp('called_at')->comment('呼叫时间');
            $table->timestamp('responded_at')->nullable()->comment('响应时间');
            $table->integer('response_seconds')->default(0)->comment('响应耗时（秒）');
            $table->string('handler', 64)->nullable()->comment('处理人');
            $table->text('result')->nullable()->comment('处理结果');
            $table->string('status', 20)->default('pending')->comment('状态: pending/responded/resolved');
            $table->timestamps();

            $table->foreign('elderly_id')->references('id')->on('kylin_elderly_profiles')->cascadeOnDelete();
            $table->index(['elderly_id', 'called_at']);
            $table->index('status');
        });

        // 6. 设备监控表
        Schema::create('kylin_elderly_device_monitors', function (Blueprint $table) {
            $table->id();
            $table->string('device_id', 64)->unique()->comment('设备编号');
            $table->unsignedBigInteger('elderly_id')->nullable()->comment('关联老人 ID');
            $table->string('device_type', 32)->comment('设备类型: monitor/wearable/bed_sensor/emergency_button');
            $table->string('status', 20)->default('offline')->comment('状态: online/offline/alarm');
            $table->timestamp('last_heartbeat')->nullable()->comment('最后心跳时间');
            $table->json('metadata')->nullable()->comment('设备元数据（JSON）');
            $table->timestamps();

            $table->foreign('elderly_id')->references('id')->on('kylin_elderly_profiles')->nullOnDelete();
            $table->index('status');
            $table->index('device_type');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('kylin_elderly_device_monitors');
        Schema::dropIfExists('kylin_elderly_emergency_calls');
        Schema::dropIfExists('kylin_elderly_medication_records');
        Schema::dropIfExists('kylin_elderly_health_records');
        Schema::dropIfExists('kylin_elderly_assessments');
        Schema::dropIfExists('kylin_elderly_profiles');
    }
};
