<?php

namespace app\http;


use app\validate\auth\ClientValidate;
use Exception;
use think\exception\ValidateException;

/**
 * 请求客户端信息
 */
readonly class HttpClient
{
    const string CLIENT_KEY = "KOhjymFZ2Ofcwvlp";

    public string $name;
    public string $id;
    public string $version;

    public array $data;

    private string $sign;

    public function __construct(string $clientName, string $clientId, string $clientVersion = '', string $sign = '')
    {
        $this->name = $clientName; // 客户端名称(PAdmin/IAdmin)
        $this->id = $clientId; // 客户端ID(前端生成的唯一标识)
        $this->version = $clientVersion; // 客户端版本号
        $this->sign = $sign; // 携带签名数据
        try {
            $this->validate();
        } catch (Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }

    private function validate(): void
    {
        $data = [];
        if ($this->sign) {
            $encryptedData = base64_decode($this->sign);
            $dataStr = openssl_decrypt($encryptedData, 'AES-128-ECB', static::CLIENT_KEY, OPENSSL_RAW_DATA);
            $data = json_decode($dataStr, true);
        }
        $this->data = $data;
        validate(ClientValidate::class)->check([
            'name' => $this->name,
            'id' => $this->id,
            'version' => $this->version,
        ]);
    }
}
