<?php
declare(strict_types=1);

namespace app\api\middleware;

use app\api\util\ReturnCode;
use plugin\saiadmin\exception\ApiException;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

/**
 * 校验对接平台 api-key（与 .env 中 API_KEY 一致）
 * 仅用于 /api/v1/* 平台对接接口
 *
 * 取值优先级（按顺序读取，首个非空即采用）：
 *  1. 请求头 api-key（推荐）
 *  2. 查询参数 api_key / api-key
 *  3. body 表单/JSON api_key / api-key
 */
class ApiKeyMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $expected = (string) config('api.platform_api_key', '');
        if ($expected === '') {
            throw new ApiException('API_KEY is not configured', ReturnCode::SERVER_ERROR);
        }

        $apiKey = $this->resolveApiKey($request);
        if ($apiKey === '') {
            throw new ApiException('Please provide api-key', ReturnCode::UNAUTHORIZED);
        }
        if (!hash_equals($expected, $apiKey)) {
            throw new ApiException('Invalid api-key', ReturnCode::FORBIDDEN);
        }

        return $handler($request);
    }

    private function resolveApiKey(Request $request): string
    {
        $headerValue = $request->header('api-key');
        if ($headerValue !== null && trim((string) $headerValue) !== '') {
            return trim((string) $headerValue);
        }

        foreach (['api_key', 'api-key'] as $key) {
            $val = $request->get($key);
            if ($val !== null && trim((string) $val) !== '') {
                return trim((string) $val);
            }
        }

        foreach (['api_key', 'api-key'] as $key) {
            $val = $request->post($key);
            if ($val !== null && trim((string) $val) !== '') {
                return trim((string) $val);
            }
        }

        return '';
    }
}
