<?php

namespace Kylin\Notification\Channels;

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

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

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

            $client = new \Kylin\Notification\JPush\Client($appKey, $masterSecret, null);

            $push = $client->push();
            $push->setPlatform($params['platform'] ?? 'all');

            // 设置受众
            if (isset($params['alias'])) {
                $push->addAlias((array) $params['alias']);
            } elseif (isset($params['tags'])) {
                $push->addAllAudience();
            } elseif (isset($params['registration_ids'])) {
                $push->addRegistrationId((array) $params['registration_ids']);
            } else {
                $push->addAllAudience();
            }

            // 设置通知内容
            $alert = $params['alert'] ?? $notification->title;
            $push->setNotificationAlert($alert);

            // Android 通知
            if (isset($params['android'])) {
                $push->androidNotification($params['android']['alert'] ?? $alert, $params['android']['extras'] ?? []);
            }

            // iOS 通知
            if (isset($params['ios'])) {
                $push->iosNotification($params['ios']['alert'] ?? $alert, $params['ios']['extras'] ?? []);
            }

            $result = $push->send();

            return [
                'success' => true,
                'message_id' => $result['body']['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 'jpush';
    }
}
