<?php

namespace App\Http\Controllers\Messenger;

use App\Http\Controllers\Controller;
use App\Http\Resources\Messenger\EventResource;
use App\Models\Messenger\UserEvent;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class UpdatesController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $request->validate([
            'since' => 'nullable|integer|min:0',
            'timeout' => 'nullable|integer|min:1|max:30',
            'channels' => 'nullable|string',
        ]);

        $userId = Auth::id();
        $since = $request->integer('since', 0);
        $timeout = $request->integer('timeout', 25); // Default 25 seconds
        $channels = $request->string('channels')->explode(',')->filter();

        $startTime = time();
        $maxWaitTime = $timeout;

        do {
            $query = UserEvent::forUser($userId)
                ->since($since)
                ->orderBy('id', 'asc')
                ->limit(100);

            // Filter by channels if specified
            if ($channels->isNotEmpty()) {
                $query->whereIn('event_type', $channels->toArray());
            }

            $events = $query->get();

            if ($events->isNotEmpty()) {
                $nextSince = $events->last()->id;
                
                return response()->json([
                    'status' => 200,
                    'message' => 'Events retrieved successfully',
                    'data' => [
                        'since' => $since,
                        'next_since' => $nextSince,
                        'events' => EventResource::collection($events),
                    ],
                ]);
            }

            // If no events, wait a bit before checking again
            if ((time() - $startTime) < $maxWaitTime) {
                sleep(1);
            }

        } while ((time() - $startTime) < $maxWaitTime);

        // No events found within timeout period
        return response()->json([
            'status' => 204,
            'message' => 'No new events',
            'data' => [
                'since' => $since,
                'next_since' => $since,
                'events' => [],
            ],
        ], 204);
    }
}
