<?php

namespace Kylin\Sms\Gateways;

use Kylin\Sms\Exceptions\GatewayException;

/**
 * Submail 赛邮短信网关
 * 
 * 支持 Submail 短信服务的发送功能
 * Submail 是国内知名的云通讯服务平台，提供短信、邮件、语音等服务
 * 
 * 文档：https://www.mysubmail.com/documents
 * 
 * @package Kylin\Sms\Gateways
 */
class SubmailGateway extends BaseGateway
{
    /**
     * 网关名称标识
     */
    protected static string $name = 'submail';

    /**
     * 普通短信发送 API 地址
     */
    protected const API_URL = 'https://api.mysubmail.com/message/send.json';

    /**
     * 模板短信发送 API 地址
     */
    protected const XSEND_API_URL = 'https://api.mysubmail.com/message/xsend.json';

    /**
     * Submail 应用 ID
     * 
     * @var string
     */
    protected string $appId;

    /**
     * Submail 应用密钥
     * 
     * @var string
     */
    protected string $appKey;

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

    /**
     * 项目 ID（模板项目）
     * 
     * @var string
     */
    protected string $projectId;

    /**
     * 构造函数
     * 
     * 初始化 Submail 短信网关配置
     * 
     * @param array $config 网关配置数组
     */
    public function __construct(array $config = [])
    {
        parent::__construct($config);
        $this->appId = $config['app_id'] ?? '';
        $this->appKey = $config['app_key'] ?? '';
        $this->signName = $config['sign_name'] ?? '';
        $this->projectId = $config['project_id'] ?? '';
    }

    /**
     * 发送短信
     * 
     * 发送普通短信内容到指定手机号
     * 
     * @param string $to 接收手机号
     * @param string $content 短信内容
     * @param array $data 附加数据
     * @return array 发送结果
     */
    public function send(string $to, string $content, array $data = []): array
    {
        $signName = $data['sign_name'] ?? $this->signName;
        $text = '【' . $signName . '】' . $content;

        $params = [
            'appid' => $this->appId,
            'to' => $this->formatPhone($to),
            'content' => $text,
        ];

        $params['signature'] = $this->computeSignature($params);

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

    /**
     * 发送模板短信
     * 
     * 使用预定义模板发送短信
     * 
     * @param string $to 接收手机号
     * @param string $templateId 模板 ID（项目 ID）
     * @param array $params 模板参数
     * @return array 发送结果
     */
    public function sendTemplate(string $to, string $templateId, array $params = []): array
    {
        $requestParams = [
            'appid' => $this->appId,
            'to' => $this->formatPhone($to),
            'project' => $templateId ?: $this->projectId,
            'vars' => json_encode($params),
        ];

        $requestParams['signature'] = $this->computeSignature($requestParams);

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

    /**
     * 批量发送短信
     * 
     * 向多个手机号发送相同内容的短信
     * 
     * @param array $recipients 接收手机号数组
     * @param string $content 短信内容
     * @param array $data 附加数据
     * @return array 发送结果
     */
    public function sendBatch(array $recipients, string $content, array $data = []): array
    {
        $results = [];
        foreach ($recipients as $recipient) {
            $results[] = $this->send($recipient, $content, $data);
        }
        return $this->buildSuccessResponse(['results' => $results]);
    }

    /**
     * 计算签名
     * 
     * 生成 Submail API 所需的签名
     * 
     * @param array $params 请求参数
     * @return string 签名字符串
     */
    protected function computeSignature(array $params): string
    {
        ksort($params);
        $queryString = http_build_query($params);
        return md5($this->appId . $this->appKey . $queryString);
    }

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

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