<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class ExpoPushService
{
    protected string $expoUrl = 'https://exp.host/--/api/v2/push/send';

    /**
     * Отправить push-уведомление одному пользователю
     */
    public function send(string $expoToken, string $title, string $body, array $data = [], string $sound = 'default'): bool
    {
        return $this->sendToMultiple([$expoToken], $title, $body, $data, $sound);
    }

    /**
     * Отправить нескольким пользователям (рекомендуется)
     */
    public function sendToMultiple(array $expoTokens, string $title, string $body, array $data = [], string $sound = 'default'): bool
    {
        if (empty($expoTokens)) {
            return false;
        }

        $messages = [];

        foreach ($expoTokens as $token) {
            $messages[] = [
                'to'       => $token,
                'title'    => $title,
                'body'     => $body,
                'data'     => $data,
                'sound'    => $sound,
                'priority' => 'high',                    // важно для Android
                'badge'    => 1,
            ];
        }

        try {
            $response = Http::timeout(15)
                ->withHeaders(['Content-Type' => 'application/json'])
                ->post($this->expoUrl, ['messages' => $messages]);

            $result = $response->json();

            // Логируем результат
            Log::info('Expo Push Response', [
                'status' => $response->status(),
                'result' => $result
            ]);

            // Проверяем ошибки от Expo
            if (isset($result['data'])) {
                foreach ($result['data'] as $item) {
                    if (isset($item['status']) && $item['status'] === 'error') {
                        Log::error('Expo Push Error', $item);
                    }
                }
            }

            return $response->successful();

        } catch (\Exception $e) {
            Log::error('Expo Push Failed', [
                'error' => $e->getMessage(),
                'tokens' => $expoTokens
            ]);
            return false;
        }
    }
}
