<?php

namespace App\Services;

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

/**
 * SocketIOService
 *
 * Laravel se Socket.IO server ko events bhejne ke liye service.
 * Ye HTTP POST karta hai Socket.IO server ke /emit endpoint pe.
 *
 * Usage:
 *   SocketIOService::emitToCircle($circleId, 'member-location-updated', $data);
 *   SocketIOService::emitToUser($userId, 'sos-alert', $data);
 */
class SocketIOService
{
    /**
     * Emit event to a specific circle room
     */
    public static function emitToCircle(int $circleId, string $event, array $data): void
    {
        self::emit($event, $data, "circle.{$circleId}");
    }

    /**
     * Emit event to multiple circle rooms
     */
    public static function emitToCircles(array $circleIds, string $event, array $data): void
    {
        foreach ($circleIds as $circleId) {
            self::emitToCircle($circleId, $event, $data);
        }
    }

    /**
     * Emit event to a specific user
     */
    public static function emitToUser(int $userId, string $event, array $data): void
    {
        self::emit($event, $data, null, "user.{$userId}");
    }

    /**
     * Broadcast event to all connected clients
     */
    public static function broadcast(string $event, array $data): void
    {
        self::emit($event, $data);
    }

    /**
     * Core emit function — POST to Socket.IO server
     */
    private static function emit(string $event, array $data, ?string $room = null, ?string $userRoom = null): void
    {
        $url = config('services.socketio.url', 'http://127.0.0.1:3000');
        $secret = config('services.socketio.secret', 'location-tracker-socket-secret-2024');

        $payload = [
            'secret' => $secret,
            'event' => $event,
            'data' => $data,
        ];

        if ($room) {
            $payload['room'] = $room;
        }

        if ($userRoom) {
            $payload['user_room'] = $userRoom;
        }

        try {
            Http::timeout(3)->post("{$url}/emit", $payload);
        } catch (\Exception $e) {
            // Socket.IO server down hai toh silently fail karo
            // API response block nahi honi chahiye
            Log::warning("SocketIO emit failed: {$e->getMessage()}", [
                'event' => $event,
                'room' => $room ?? $userRoom ?? 'broadcast',
            ]);
        }
    }
}
