<?php

namespace App\Http\Controllers;

use App\Models\Notificacao;
use Illuminate\Http\JsonResponse;

class NotificacaoController extends Controller
{
    public function index(): JsonResponse
    {
        $lista = Notificacao::where('user_id', auth()->id())
            ->latest()
            ->take(25)
            ->get();

        return response()->json([
            'notificacoes' => $lista,
            'unread'       => $lista->whereNull('lida_em')->count(),
        ]);
    }

    public function markAllRead(): JsonResponse
    {
        Notificacao::where('user_id', auth()->id())
            ->whereNull('lida_em')
            ->update(['lida_em' => now()]);

        return response()->json(['ok' => true]);
    }

    public function markRead(Notificacao $notificacao): JsonResponse
    {
        abort_unless($notificacao->user_id === auth()->id(), 403);
        $notificacao->update(['lida_em' => now()]);
        return response()->json(['ok' => true]);
    }
}
