<?php

namespace Kylin\Fitness\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * API Key 验证中间件
 *
 * 验证设备 API Key，用于 InBody 等体测设备对接。
 */
class ApiKeyMiddleware
{
    /**
     * 验证设备 API Key
     * 用于 InBody 等体测设备对接
     */
    public function handle(Request $request, Closure $next): Response
    {
        $apiKey = $request->header('X-API-Key') ?? $request->query('api_key');
        $validKey = config('fitness.device_api_key');

        if (!$validKey || !$apiKey || !hash_equals($validKey, $apiKey)) {
            return response()->json([
                'code' => 401,
                'message' => '无效的 API Key',
            ], 401);
        }

        return $next($request);
    }
}
