<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

/**
 * In-app notification read API (Team Workspaces P3d / Δ25). Marks the AppNav
 * bell's notifications read. JSON-returning: the bell calls these via plain
 * `fetch` (fire-and-forget on item-click so it never races the Inertia
 * navigation), then `router.reload({ only: ['notifications'] })` to refresh
 * the shared prop. SaaS-only. `index()` is the full-history page behind the
 * bell's "View all" link.
 */
class NotificationController extends Controller
{
    /**
     * GET /notifications — full notification history (all, newest-first,
     * paginated). The bell ships only the latest 10; this is "View all".
     * The paginated list is shipped as `feed` (NOT `notifications` — that
     * name is the shared bell prop on every app surface).
     */
    public function index(Request $request): Response
    {
        $user = $request->user();

        // Type filter → notification categories. Unknown/absent = all.
        $typeCategories = [
            'projects' => ['project.created', 'project.deleted', 'project.shared', 'project.revoked'],
            'members' => ['role'],
            'invites' => ['invite'],
        ];
        $type = (string) $request->query('type', 'all');

        $query = $user->notifications()->latest();
        if (isset($typeCategories[$type])) {
            $query->whereIn('data->category', $typeCategories[$type]);
        } else {
            $type = 'all';
        }

        $feed = $query
            ->paginate(20)
            ->withQueryString()
            ->through(fn ($n) => [
                'id' => (string) $n->id,
                'title' => $n->data['title'] ?? '',
                'body' => $n->data['body'] ?? '',
                'url' => $n->data['url'] ?? null,
                'workspace' => $n->data['workspace'] ?? null,
                'category' => $n->data['category'] ?? null,
                'read_at' => $n->read_at?->toIso8601String(),
                'created_at' => $n->created_at?->toIso8601String(),
            ]);

        return Inertia::render('Notifications/Index', [
            'feed' => $feed,
            'unread_count' => (int) $user->unreadNotifications()->count(),
            'filters' => ['type' => $type],
        ]);
    }

    /**
     * POST /notifications/{id}/read — mark a single notification read. Scoped
     * to the acting user's own notifications (a foreign id is a no-op, never a
     * cross-user read).
     */
    public function read(Request $request, string $id): JsonResponse
    {
        $request->user()
            ->unreadNotifications()
            ->where('id', $id)
            ->update(['read_at' => now()]);

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

    /**
     * POST /notifications/read-all — mark every unread notification read.
     */
    public function readAll(Request $request): JsonResponse
    {
        $request->user()->unreadNotifications->markAsRead();

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