<?php

namespace Kylin\Sms\Gateways;

use Kylin\Sms\Exceptions\GatewayException;

/**
 * 融合云（助通）短信网关
 * 
 * 支持融合云短信服务的发送功能
 * 融合云是助通科技旗下的云通讯平台，提供企业级短信发送服务
 * 
 * 文档：https://www.ztinfo.cn/
 * 
 * @package Kylin\Sms\Gateways
 */
class RongheyunGateway extends BaseGateway
{
    /**
     * 网关名称标识
     */
    protected static string $name = 'rongheyun';

    /**
     * API 请求地址
     */
    protected const API_URL = 'https://api.mix2.zthysms.com/v2/sendSmsTp';

    /**
     * 用户名
     * 
     * @var string
     */
    protected string $username;

    /**
     * 密码
     * 
     * @var string
     */
    protected string $password;

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

    /**
     * 构造函数
     * 
     * 初始化融合云短信网关配置
     * 
     * @param array $config 网关配置数组
     */
    public function __construct(array $config = [])
    {
        parent::__construct($config);
        $this->username = $config['username'] ?? '';
        $this->password = $config['password'] ?? '';
        $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
    {
        $tKey = time();
        $password = md5($this->password . $tKey);

        $params = [
            'username' => $this->username,
            'password' => $password,
            'tKey' => $tKey,
            'mobile' => $this->formatPhone($to),
            'tpId' => $data['template_id'] ?? '',
            'record' => 'false',
            'ext' => '',
        ];

        $templateParams = $data['template_params'] ?? [];
        foreach ($templateParams as $key => $value) {
            $params['tpContent'][$key] = $value;
        }

        if (!empty($templateParams)) {
            $params['tpContent'] = json_encode($params['tpContent']);
        }

        try {
            $response = $this->request('POST', self::API_URL, [
                '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
    {
        $tKey = time();
        $password = md5($this->password . $tKey);

        $params = [
            'username' => $this->username,
            'password' => $password,
            'tKey' => $tKey,
            'mobile' => implode(',', array_map([$this, 'formatPhone'], $recipients)),
            'tpId' => $data['template_id'] ?? '',
            'record' => 'false',
            'ext' => '',
        ];

        $templateParams = $data['template_params'] ?? [];
        foreach ($templateParams as $key => $value) {
            $params['tpContent'][$key] = $value;
        }

        if (!empty($templateParams)) {
            $params['tpContent'] = json_encode($params['tpContent']);
        }

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

    /**
     * 解析响应结果
     * 
     * 将融合云 API 响应转换为标准化的结果格式
     * 
     * @param array $response API 响应
     * @return array 标准化的响应结果
     */
    protected function parseResponse(array $response): array
    {
        if (isset($response['code']) && $response['code'] === 200) {
            return $this->buildSuccessResponse([
                'msg_id' => $response['msgId'] ?? '',
                'success_count' => $response['successNum'] ?? 0,
            ]);
        }

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