<?php

namespace Kylin\Notification\Channels;

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

/**
 * 友盟推送渠道
 * 通过 HTTP API 直接调用，签名方式简单
 * API文档：https://developer.umeng.com/docs/66632/detail/68343
 */
class UMengChannel implements ChannelInterface
{
    public function send(Notification $notification, array $params = []): array
    {
        try {
            $platform = $params['platform'] ?? 'android'; // android | ios
            $config = config("kylin-notification.channels.umeng.{$platform}", []);

            $appKey = $config['app_key'] ?? '';
            $appMasterSecret = $config['app_master_secret'] ?? '';

            if (!$appKey || !$appMasterSecret) {
                return ['success' => false, 'message_id' => null, 'error' => 'UMeng not configured', 'raw_response' => null];
            }

            $timestamp = (string) time();
            $method = strtoupper($params['method'] ?? 'POST');
            $url = '/api/send';

            // 构建消息体
            $payload = [
                'appkey' => $appKey,
                'timestamp' => $timestamp,
                'type' => $params['type'] ?? 'customizedcast',
                'alias_type' => $params['alias_type'] ?? 'user_id',
                'alias' => $params['alias'] ?? '',
                'payload' => [
                    'display_type' => 'notification',
                    'body' => [
                        'title' => $params['title'] ?? $notification->title,
                        'text' => $params['text'] ?? $notification->content,
                        'ticker' => $params['ticker'] ?? $notification->title,
                        'after_open' => $params['after_open'] ?? 'go_app',
                    ],
                    'extra' => $params['extra'] ?? [],
                ],
            ];

            // 计算签名
            $postBody = json_encode($payload);
            $sign = md5("{$method}{$url}{$postBody}{$appMasterSecret}");

            $client = new Client();
            $response = $client->post("https://msgapi.umeng.com{$url}", [
                'query' => ['sign' => $sign],
                'json' => $payload,
            ]);

            $result = json_decode($response->getBody()->getContents(), true);
            $success = ($result['ret'] ?? '') === 'SUCCESS';

            return [
                'success' => $success,
                'message_id' => $result['data']['task_id'] ?? null,
                'error' => $success ? null : ($result['data']['error_code'] ?? 'Unknown error'),
                'raw_response' => $result,
            ];
        } catch (\Throwable $e) {
            return ['success' => false, 'message_id' => null, 'error' => $e->getMessage(), 'raw_response' => null];
        }
    }

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