<?php

namespace App\Modules\Dashboard\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Dashboard\Requests\BulkMarkNotificationsReadRequest;
use App\Modules\Dashboard\Requests\NotificationIndexRequest;
use App\Modules\Dashboard\Services\NotificationCenterService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

class NotificationCenterController extends Controller
{
    public function __construct(
        private readonly NotificationCenterService $notifications,
    ) {}

    public function index(NotificationIndexRequest $request): View
    {
        $user = $request->user();
        $categoryFilter = $request->filterCategory();
        $paginator = $this->notifications->paginate($user, $categoryFilter);
        $activeType = $request->input('type', 'all');

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

    public function markRead(Request $request, string $id): RedirectResponse
    {
        if (! Str::isUuid($id)) {
            abort(404);
        }
        $ok = $this->notifications->markRead($request->user(), $id);
        if (! $ok) {
            abort(404);
        }

        return back()->with('status', __('notifications.marked_read'));
    }

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

        return back()->with('status', __('notifications.marked_all_read'));
    }

    public function markManyRead(BulkMarkNotificationsReadRequest $request): RedirectResponse
    {
        $result = $this->notifications->markManyRead($request->user(), $request->validated('ids'));

        return back()->with('bulk_result', $result->toSessionPayload());
    }
}
