<?php

namespace App\Http\Controllers;

use App\Models\Notification;
use App\Services\NotificationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class NotificationController extends Controller
{
    public function index(Request $request, NotificationService $notifications): View
    {
        $user = $request->user();

        abort_unless($user !== null && $user->hasPermission('notifications.view'), 403);

        $notifications->generateOperationalAlerts();

        $items = Notification::query()
            ->where('user_id', $user->id)
            ->orderByDesc('created_at')
            ->paginate(20);

        return view('notifications.index', [
            'notifications' => $items,
            'unreadCount' => $notifications->unreadCount($user->id),
        ]);
    }

    public function markRead(Notification $notification, NotificationService $notifications): RedirectResponse
    {
        abort_unless(
            auth()->id() === $notification->user_id && auth()->user()?->hasPermission('notifications.view'),
            403,
        );

        $notifications->markRead($notification);

        return back()->with('success', 'Notification marked as read.');
    }

    public function markAllRead(Request $request, NotificationService $notifications): RedirectResponse
    {
        $user = $request->user();

        abort_unless($user !== null && $user->hasPermission('notifications.view'), 403);

        $count = $notifications->markAllRead($user->id);

        return back()->with('success', "{$count} notification(s) marked as read.");
    }
}
