<?php

namespace Kylin\Notification\AlibabaCloud;

use GuzzleHttp\Client;

/**
 * 阿里云短信发送封装
 * 基于 Dysmsapi 2017-05-25 API，使用 HTTP 直接调用
 * API文档：https://help.aliyun.com/document_detail/419277.html
 */
class DysmsapiClient
{
    private string $accessKeyId;
    private string $accessKeySecret;
    private string $endpoint;

    public function __construct(array $config)
    {
        $this->accessKeyId = $config['access_key'] ?? '';
        $this->accessKeySecret = $config['access_secret'] ?? '';
        $this->endpoint = $config['endpoint'] ?? 'dysmsapi.aliyuncs.com';
    }

    /**
     * 发送短信
     */
    public function sendSms(array $params): array
    {
        $apiParams = [
            'PhoneNumbers' => $params['PhoneNumbers'],
            'SignName' => $params['SignName'],
            'TemplateCode' => $params['TemplateCode'],
            'TemplateParam' => $params['TemplateParam'] ?? '{}',
            'Action' => 'SendSms',
            'Version' => '2017-05-25',
            'Format' => 'JSON',
            'RegionId' => 'cn-hangzhou',
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureVersion' => '1.0',
            'SignatureNonce' => uniqid(),
            'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
            'AccessKeyId' => $this->accessKeyId,
        ];

        // 计算签名
        ksort($apiParams);
        $sortedQueryString = http_build_query($apiParams, '', '&', PHP_QUERY_RFC3986);
        $stringToSign = 'POST&%2F&' . rawurlencode($sortedQueryString);
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $this->accessKeySecret . '&', true));

        $apiParams['Signature'] = $signature;

        $client = new Client();
        $response = $client->post("https://{$this->endpoint}/", [
            'form_params' => $apiParams,
        ]);

        return json_decode($response->getBody()->getContents(), true);
    }
}
