<?php

namespace Kylin\Notification\Channels;

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

class GeTuiChannel implements ChannelInterface
{
    public function send(Notification $notification, array $params = []): array
    {
        try {
            $config = config('kylin-notification.channels.getui', []);
            $appId = $config['app_id'] ?? '';
            $appKey = $config['app_key'] ?? '';
            $masterSecret = $config['master_secret'] ?? '';

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

            $client = new \Kylin\Notification\GeTui\GTClient($appId, $appKey, $masterSecret);

            // 构建推送消息
            $pushApi = $client->pushApi();

            $message = new \Kylin\Notification\GeTui\request\push\GTPushMessage();
            $notification = new \Kylin\Notification\GeTui\request\push\GTNotification();
            $notification->setTitle($params['title'] ?? $notification->title);
            $notification->setBody($params['body'] ?? $notification->content);

            if (isset($params['click_type'])) {
                $notification->setClickType($params['click_type']);
            }

            $message->setNotification($notification);

            // 设置推送目标
            if (isset($params['cid'])) {
                $result = $pushApi->pushToSingleByCid($params['cid'], $message);
            } elseif (isset($params['cid_list'])) {
                $result = $pushApi->pushToList($params['cid_list'], $message);
            } else {
                $result = $pushApi->pushToApp($message);
            }

            return [
                'success' => true,
                'message_id' => $result['taskid'] ?? $result['msg_id'] ?? null,
                'error' => null,
                'raw_response' => $result,
            ];
        } catch (\Throwable $e) {
            return ['success' => false, 'message_id' => null, 'error' => $e->getMessage(), 'raw_response' => null];
        }
    }

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