<?php

namespace Kylin\Sms\Gateways;

use Kylin\Sms\Exceptions\GatewayException;

/**
 * 七牛云短信网关
 * 
 * 支持七牛云短信服务的发送功能
 * 七牛云是国内领先的云服务商，提供稳定可靠的短信发送能力
 * 
 * 文档：https://developer.qiniu.com/sms
 * 
 * @package Kylin\Sms\Gateways
 */
class QiniuGateway extends BaseGateway
{
    /**
     * 网关名称标识
     */
    protected static string $name = 'qiniu';

    /**
     * API 请求地址
     */
    protected const API_URL = 'https://sms.qiniuapi.com/v1/message';

    /**
     * 七牛云 Access Key
     * 
     * @var string
     */
    protected string $accessKey;

    /**
     * 七牛云 Secret Key
     * 
     * @var string
     */
    protected string $secretKey;

    /**
     * 短信签名
     * 
     * @var string
     */
    protected string $signName;

    /**
     * 构造函数
     * 
     * 初始化七牛云短信网关配置
     * 
     * @param array $config 网关配置数组
     */
    public function __construct(array $config = [])
    {
        parent::__construct($config);
        $this->accessKey = $config['access_key'] ?? '';
        $this->secretKey = $config['secret_key'] ?? '';
        $this->signName = $config['sign_name'] ?? '';
    }

    /**
     * 发送短信
     * 
     * 发送短信到指定手机号
     * 
     * @param string $to 接收手机号
     * @param string $content 短信内容（七牛云使用模板，此参数可忽略）
     * @param array $data 附加数据，包含 template_id 和 template_params
     * @return array 发送结果
     */
    public function send(string $to, string $content, array $data = []): array
    {
        $params = [
            'template_id' => $data['template_id'] ?? '',
            'mobiles' => [$this->formatPhone($to)],
            'parameters' => $data['template_params'] ?? [],
        ];

        $headers = $this->buildHeaders($params);

        try {
            $response = $this->request('POST', self::API_URL, [
                'headers' => $headers,
                'json' => $params,
            ]);
            return $this->parseResponse($response);
        } catch (GatewayException $e) {
            return $this->buildErrorResponse($e->getMessage(), $e->getCode(), $e->getContext());
        }
    }

    /**
     * 发送模板短信
     * 
     * 使用预定义模板发送短信
     * 
     * @param string $to 接收手机号
     * @param string $templateId 模板 ID
     * @param array $params 模板参数
     * @return array 发送结果
     */
    public function sendTemplate(string $to, string $templateId, array $params = []): array
    {
        return $this->send($to, '', [
            'template_id' => $templateId,
            'template_params' => $params,
        ]);
    }

    /**
     * 批量发送短信
     * 
     * 向多个手机号发送相同内容的短信
     * 
     * @param array $recipients 接收手机号数组
     * @param string $content 短信内容
     * @param array $data 附加数据
     * @return array 发送结果
     */
    public function sendBatch(array $recipients, string $content, array $data = []): array
    {
        $params = [
            'template_id' => $data['template_id'] ?? '',
            'mobiles' => array_map([$this, 'formatPhone'], $recipients),
            'parameters' => $data['template_params'] ?? [],
        ];

        $headers = $this->buildHeaders($params);

        try {
            $response = $this->request('POST', self::API_URL, [
                'headers' => $headers,
                'json' => $params,
            ]);
            return $this->parseResponse($response);
        } catch (GatewayException $e) {
            return $this->buildErrorResponse($e->getMessage(), $e->getCode(), $e->getContext());
        }
    }

    /**
     * 构建请求头
     * 
     * 生成七牛云 API 所需的认证头信息
     * 
     * @param array $params 请求参数
     * @return array 请求头数组
     */
    protected function buildHeaders(array $params): array
    {
        $data = json_encode($params);
        $url = parse_url(self::API_URL);
        $path = $url['path'];
        $host = $url['host'];

        $contentType = 'application/json';
        $date = gmdate('D, d M Y H:i:s \G\M\T');

        $stringToSign = "POST {$path}\nHost: {$host}\nContent-Type: {$contentType}\n\n{$data}";
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $this->secretKey, true));
        $authorization = "QBox {$this->accessKey}:{$signature}";

        return [
            'Authorization' => $authorization,
            'Content-Type' => $contentType,
            'Host' => $host,
            'Date' => $date,
        ];
    }

    /**
     * 解析响应结果
     * 
     * 将七牛云 API 响应转换为标准化的结果格式
     * 
     * @param array $response API 响应
     * @return array 标准化的响应结果
     */
    protected function parseResponse(array $response): array
    {
        if (isset($response['job_id'])) {
            return $this->buildSuccessResponse([
                'job_id' => $response['job_id'],
            ]);
        }

        return $this->buildErrorResponse(
            $response['error'] ?? '发送失败',
            $response['code'] ?? 500,
            $response
        );
    }
}
