<?php

namespace App\Http\Controllers\Api\V1\Admin;

use App\Events\BroadcastSent;
use App\Http\Controllers\Controller;
use App\Models\Broadcast;
use App\Models\User;
use App\Services\FirebaseService;
use Illuminate\Http\Request;

class BroadcastController extends Controller
{
    public function __construct(private FirebaseService $firebase) {}

    public function index(Request $request)
    {
        $broadcasts = Broadcast::with('event:id,name')
            ->latest()
            ->paginate(20);

        return $this->paginated($broadcasts);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title'    => ['required', 'string', 'max:255'],
            'body'     => ['required', 'string'],
            'target'   => ['required', 'in:all,event'],
            'event_id' => ['required_if:target,event', 'nullable', 'integer', 'exists:events,id'],
        ]);

        $broadcast = Broadcast::create([
            ...$data,
            'created_by_admin_id' => $request->user()->id,
            'sent_at'             => now(),
        ]);

        if ($broadcast->target === 'all') {
            $this->firebase->sendToTopic(
                config('firebase.broadcast_topic', 'all_users'),
                $broadcast->title,
                $broadcast->body,
                ['type' => 'broadcast', 'broadcast_id' => (string) $broadcast->id],
            );
        } else {
            $tokens = User::whereHas('registrations', fn ($q) =>
                    $q->where('event_id', $broadcast->event_id)
                      ->where('status', '!=', 'cancelled')
                )->whereNotNull('fcm_token')
                ->pluck('fcm_token')
                ->toArray();

            $this->firebase->sendToTokens(
                $tokens,
                $broadcast->title,
                $broadcast->body,
                ['type' => 'broadcast', 'broadcast_id' => (string) $broadcast->id],
            );
        }

        BroadcastSent::dispatch($broadcast);

        return $this->created($broadcast->load('event:id,name'), 'Broadcast sent.');
    }

    public function destroy(Request $request, Broadcast $broadcast)
    {
        $broadcast->delete();

        return $this->noContent('Broadcast deleted.');
    }
}
