/**
 * Dashboard Notifications API
 *
 * GET  - Fetch user notifications with pagination
 * PATCH - Mark notifications as read
 *
 * All data via Convex. No Prisma.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { logger } from "@/lib/logger";
import { withCSRF } from "@/lib/csrf";
import { convexQuery, convexMutation } from "@/lib/convex-client";

const log = logger.scope("NotificationsAPI");

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const limit = Math.min(
      100,
      parseInt(request.nextUrl.searchParams.get("limit") || "20"),
    );
    const offset = parseInt(request.nextUrl.searchParams.get("offset") || "0");

    const result = await convexQuery<unknown[]>(
      "notifications/queries:getNotifications",
      { userId: user.userId, limit },
    );

    const notifications = Array.isArray(result) ? result : [];
    const unreadCount = notifications.filter(
      (n: unknown) => !(n as Record<string, unknown>).isRead,
    ).length;

    return NextResponse.json({
      success: true,
      notifications,
      total: notifications.length,
      unreadCount,
      pagination: { limit, offset, hasMore: false },
    });
  } catch (error) {
    log.error("Failed to get notifications", {
      error: error instanceof Error ? error.message : String(error),
    });
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export const PATCH = withCSRF(async (request: NextRequest) => {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const body = await request.json();
    const { notificationIds, markAllAsRead } = body;

    if (markAllAsRead) {
      const result = await convexMutation<{ updated: number }>(
        "notifications/mutations:markAllRead",
        { userId: user.userId },
      );
      return NextResponse.json({
        success: true,
        updatedCount: result?.updated ?? 0,
      });
    }

    if (
      notificationIds &&
      Array.isArray(notificationIds) &&
      notificationIds.length > 0
    ) {
      await Promise.all(
        notificationIds.map((id: string) =>
          convexMutation("notifications/mutations:markRead", { id }),
        ),
      );
      return NextResponse.json({
        success: true,
        updatedCount: notificationIds.length,
      });
    }

    return NextResponse.json(
      { success: false, error: "No notifications specified" },
      { status: 400 },
    );
  } catch (error) {
    log.error("Failed to mark notifications as read", {
      error: error instanceof Error ? error.message : String(error),
    });
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
});
