<?php

namespace Kylin\Notification\Channels;

use Kylin\Notification\Contracts\ChannelInterface;
use Kylin\Notification\Models\Notification;

/**
 * 微信模板消息渠道
 * 依赖 kylin/wechat 包（合并自原 wechat-sdk + wechat-bridge）
 */
class WechatTemplateChannel implements ChannelInterface
{
    public function send(Notification $notification, array $params = []): array
    {
        try {
            $openid = $params['openid'] ?? $params['to'] ?? null;
            $templateId = $params['template_id'] ?? '';
            $data = $params['data'] ?? [];
            $url = $params['url'] ?? '';
            $miniprogram = $params['miniprogram'] ?? [];

            if (!$openid) {
                return ['success' => false, 'message_id' => null, 'error' => 'Missing openid', 'raw_response' => null];
            }

            if (!$templateId) {
                return ['success' => false, 'message_id' => null, 'error' => 'Missing template_id', 'raw_response' => null];
            }

            // 使用 EasyWeChat 或 kylin/wechat 发送
            $app = app('wechat.official_account');
            $api = $app->getTemplateMessage();

            $messageData = [
                'touser' => $openid,
                'template_id' => $templateId,
                'data' => $data,
            ];

            if ($url) {
                $messageData['url'] = $url;
            }

            if ($miniprogram) {
                $messageData['miniprogram'] = $miniprogram;
            }

            $result = $api->send($messageData);

            return [
                'success' => isset($result['msgid']),
                'message_id' => $result['msgid'] ?? null,
                'error' => isset($result['errmsg']) && $result['errmsg'] !== 'ok' ? $result['errmsg'] : null,
                'raw_response' => $result,
            ];
        } catch (\Throwable $e) {
            return ['success' => false, 'message_id' => null, 'error' => $e->getMessage(), 'raw_response' => null];
        }
    }

    public function getName(): string
    {
        return 'wechat_template';
    }
}
