<?php

namespace App\Services\Providers;

use App\Models\DeviceToken;
use Illuminate\Support\Facades\Http;
use RuntimeException;

class ExpoPushProvider
{
    public function send(DeviceToken $device, string $title, string $body, array $data = []): ?string
    {
        if (! config('clinic.expo.enabled')) {
            throw new RuntimeException('Expo push provider is disabled.');
        }

        $response = Http::timeout(15)
            ->acceptJson()
            ->post(config('clinic.expo.url'), [
                'to' => $device->token,
                'title' => $title,
                'body' => $body,
                'data' => $data,
                'sound' => 'default',
            ])
            ->throw()
            ->json();

        $ticket = $response['data'] ?? $response;
        if (($ticket['status'] ?? null) === 'error') {
            $message = $ticket['message'] ?? 'Expo rejected the push token.';
            throw new RuntimeException($message);
        }

        return $ticket['id'] ?? null;
    }
}
