<?php

namespace App\Http\Controllers;

use App\Models\Notification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    /**
     * Poll new unread notifications.
     * Marks them as read instantly so they are only toasted once.
     */
    public function poll()
    {
        $userId = Auth::id();
        if (!$userId) {
            return response()->json([]);
        }

        $unread = Notification::where('user_id', $userId)
            ->where('is_read', false)
            ->get();

        if ($unread->isNotEmpty()) {
            // Mark as read immediately
            Notification::where('user_id', $userId)
                ->whereIn('id', $unread->pluck('id'))
                ->update(['is_read' => true]);
        }

        return response()->json($unread);
    }
}
