<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\UserNotificationResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class NotificationController extends Controller
{
    /**
     * § 9 — notifications non lues de l’utilisateur connecté.
     */
    public function index(Request $request): AnonymousResourceCollection
    {
        $paginator = $request->user()
            ->unreadNotifications()
            ->orderByDesc('created_at')
            ->paginate((int) $request->integer('per_page', 15));

        return UserNotificationResource::collection($paginator);
    }

    /** Marquer une notification comme lue (ex. après ouverture en app mobile). */
    public function markAsRead(Request $request, string $id): JsonResponse
    {
        $notification = $request->user()->notifications()->whereKey($id)->firstOrFail();

        if ($notification->read_at === null) {
            $notification->markAsRead();
        }

        return response()->json(['message' => __('Notification lue.')]);
    }
}
