<?php

namespace Kylin\Sms\Gateways;

use Kylin\Sms\Exceptions\GatewayException;

/**
 * 微趣云短信网关
 * 
 * 支持微趣云短信服务的发送功能
 * 文档：https://www.weiquyun.com/
 */
class WeiquyunGateway extends BaseGateway
{
    protected static string $name = 'weiquyun';

    protected const API_URL = 'https://api.weiquyun.com/sms/send';

    protected string $appId;
    protected string $appKey;
    protected string $signName;

    public function __construct(array $config = [])
    {
        parent::__construct($config);
        $this->appId = $config['app_id'] ?? '';
        $this->appKey = $config['app_key'] ?? '';
        $this->signName = $config['sign_name'] ?? '';
    }

    public function send(string $to, string $content, array $data = []): array
    {
        $timestamp = time();
        $sign = md5($this->appId . $this->appKey . $timestamp);

        $params = [
            'appId' => $this->appId,
            'timestamp' => $timestamp,
            'sign' => $sign,
            'mobile' => $this->formatPhone($to),
            'templateId' => $data['template_id'] ?? '',
            'params' => json_encode($data['template_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());
        }
    }

    public function sendTemplate(string $to, string $templateId, array $params = []): array
    {
        return $this->send($to, '', [
            'template_id' => $templateId,
            'template_params' => $params,
        ]);
    }

    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]);
    }

    protected function parseResponse(array $response): array
    {
        if (isset($response['code']) && $response['code'] === 0) {
            return $this->buildSuccessResponse([
                'sms_id' => $response['data']['smsId'] ?? '',
            ]);
        }

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