<?php

namespace App\Events;

use App\Models\Alert;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class EmergencyAlertBroadcast implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $alertData;

    public function __construct(Alert $alert)
    {
        // Construct clean JSON matching parameters expected by Android client sockets
        $this->alertData = [
            'id'        => $alert->id,
            'user_name' => $alert->user->name ?? 'Anonymous User',
            'latitude'  => (float) $alert->latitude,
            'longitude' => (float) $alert->longitude,
            'video_url' => $alert->video_path ? asset('storage/' . $alert->video_path) : null,
            'tagged_at' => $alert->tagged_at->toDateTimeString(),
        ];
    }

    public function broadcastOn(): array
    {
        // Public channel configuration map matching Android's tracking route strings
        return [
            new Channel('security-alerts-channel')
        ];
    }

    public function broadcastAs(): string
    {
        return 'incoming-alert';
    }
}
