<?php

namespace App\Http\Controllers\Notification;

use App\Http\Controllers\Controller;
use App\Models\Notification;
use App\Services\NotificationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class NotificationController extends Controller
{
    public function __construct(private readonly NotificationService $notificationService)
    {
    }

    public function index(): View
    {
        $notifications = auth()->user()->notifications()->latest()->paginate(20);

        $this->notificationService->markAllRead(auth()->user());

        return view('notifications.index', compact('notifications'));
    }

    /**
     * Endpoint سبک برای Bell — هر ۱۵ ثانیه Poll می‌شود (هم‌راستا با Chat در Phase 11).
     */
    public function poll(): JsonResponse
    {
        $user = auth()->user();

        $recent = $user->notifications()->latest()->limit(5)->get()->map(fn (Notification $n) => [
            'id' => $n->id,
            'title' => $n->title,
            'body' => $n->body,
            'action_url' => $n->action_url,
            'is_read' => $n->isRead(),
            'created_at' => verta($n->created_at)->format('H:i'),
        ]);

        return response()->json([
            'unread_count' => $this->notificationService->unreadCountFor($user),
            'recent' => $recent,
        ]);
    }

    public function markRead(Notification $notification): RedirectResponse
    {
        $this->authorize('markRead', $notification);

        $this->notificationService->markRead($notification);

        return redirect($notification->action_url ?: url()->previous());
    }
}
