<?php
namespace EasyChat\Library\Queue\Jobs;

use EasyChat\Library\AndroidPushNotifier;
use EasyChat\Library\Queue\JobInterface;

 
class SmsInboundPushJob implements JobInterface {
    private $registry;

    public function __construct($registry) {
        $this->registry = $registry;
    }

    public function handle(array $payload): void {
        $chat_id = (int)($payload['chat_id'] ?? 0);
        $message_id = (int)($payload['message_id'] ?? 0);
        $channel = strtolower(trim((string)($payload['channel'] ?? '')));
        if ($chat_id <= 0 || $message_id <= 0 || !in_array($channel, ['fcm', 'webpush'], true)) {
            throw new \InvalidArgumentException('sms_inbound_push_payload_invalid');
        }

         
         
        $result = (new AndroidPushNotifier($this->registry))->notifyNewMessage(
            $chat_id,
            'sms',
            '',
            'SMS',
            [$channel]
        );
        if (!$this->deliveryAccepted($result, $channel)) {
            $code = preg_replace('/[^a-z0-9._-]/i', '_', (string)($result['error'] ?? 'sms_inbound_push_failed'));
            throw new \RuntimeException(substr($code, 0, 80));
        }
    }

    private function deliveryAccepted(array $result, string $channel): bool {
        if (!empty($result['fanout'])) {
            $accepted = (int)($result[$channel . '_sent'] ?? 0) > 0;
             
             
            if (!$accepted
                && $channel === 'webpush'
                && !empty($result['success'])
                && (int)($result['target_count'] ?? -1) === 0
                && (int)($result['failed'] ?? 0) === 0
                && (int)($result['webpush_failed'] ?? 0) === 0) {
                return true;
            }
            return $accepted;
        }
        return $channel === 'fcm' && (int)($result['sent'] ?? 0) > 0;
    }
}
