<?php

namespace Kylin\Notification\Channels;

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

class AliyunSmsChannel implements ChannelInterface
{
    public function send(Notification $notification, array $params = []): array
    {
        try {
            $phone = $params['phone'] ?? $params['to'] ?? null;
            $signName = $params['sign_name'] ?? config('kylin-notification.channels.aliyun_sms.sign_name', '');
            $templateCode = $params['template_code'] ?? '';
            $templateParams = $params['template_params'] ?? [];

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

            $config = config('kylin-notification.channels.aliyun_sms', []);
            $client = new DysmsapiClient($config);

            $result = $client->sendSms([
                'PhoneNumbers' => $phone,
                'SignName' => $signName,
                'TemplateCode' => $templateCode,
                'TemplateParam' => json_encode($templateParams),
            ]);

            $code = $result['Code'] ?? 'UNKNOWN';
            $success = $code === 'OK';

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

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