<?php

declare(strict_types=1);

namespace Kylin\Fitness\Http\Controllers\Device;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Kylin\Fitness\Models\FitnessTest;
use Kylin\Fitness\Models\Member;
use Kylin\Fitness\Services\FitnessTestEncryptor;

/**
 * InBody 体测设备同步控制器
 *
 * 接收 InBody 体测设备推送数据，遵循 GB/T 31267-2014 体测设备数据接口规范。
 *
 * 依据《个人信息保护法》第二十八条：
 * 体测数据属于敏感个人信息，同步时需加密存储。
 */
class InBodySyncController extends Controller
{
    /**
     * 接收 InBody 体测设备推送数据
     *
     * GB/T 31267-2014 体测设备数据接口规范：
     * - 数据完整性校验
     * - 会员身份验证
     * - 体测数据加密存储
     */
    public function sync(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'member_phone' => 'required|string',
            'test_date' => 'required|date',
            'height' => 'nullable|numeric',
            'weight' => 'nullable|numeric',
            'body_fat_rate' => 'nullable|numeric',
            'muscle_mass' => 'nullable|numeric',
            'basal_metabolic_rate' => 'nullable|numeric',
            'visceral_fat_level' => 'nullable|integer',
            'bmi' => 'nullable|numeric',
            'body_water' => 'nullable|numeric',
            'bone_mass' => 'nullable|numeric',
            'device_model' => 'nullable|string',
            'raw_data' => 'nullable|string',
        ]);

        $member = Member::where('phone', $validated['member_phone'])->first();
        if (! $member) {
            return response()->json([
                'code' => 404,
                'message' => '会员不存在',
            ], 404);
        }

        // 体测数据加密（依据《个人信息保护法》第二十八条）
        $encryptEnabled = config('fitness.fitness_test_encryption', true);
        $rawData = $validated['raw_data'] ?? null;
        if ($encryptEnabled && $rawData !== null) {
            $rawData = FitnessTestEncryptor::encrypt(json_decode($rawData, true) ?? ['raw' => $rawData]);
        }

        $test = FitnessTest::create([
            'member_id' => $member->id,
            'test_date' => $validated['test_date'],
            'height' => $validated['height'] ?? null,
            'weight' => $validated['weight'] ?? null,
            'body_fat_rate' => $validated['body_fat_rate'] ?? null,
            'muscle_mass' => $validated['muscle_mass'] ?? null,
            'basal_metabolic_rate' => $validated['basal_metabolic_rate'] ?? null,
            'visceral_fat_level' => $validated['visceral_fat_level'] ?? null,
            'bmi' => $validated['bmi'] ?? null,
            'body_water' => $validated['body_water'] ?? null,
            'bone_mass' => $validated['bone_mass'] ?? null,
            'data_source' => 'inbody',
            'device_model' => $validated['device_model'] ?? 'InBody',
            'raw_data' => $rawData,
        ]);

        return response()->json([
            'code' => 200,
            'message' => '数据同步成功',
            'data' => ['test_id' => $test->id],
        ]);
    }
}