import { NextRequest, NextResponse } from "next/server";
import { db, notifications, users, eq, and, desc, count } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";

export async function GET(req: NextRequest) {
  const { session, response } = await requireSession();
  if (response) return response;

  const { searchParams } = req.nextUrl;
  const limitRaw = parseInt(searchParams.get("limit") ?? "20");
  const limit = Math.min(Number.isNaN(limitRaw) ? 20 : Math.max(1, limitRaw), 100);
  const offsetRaw = parseInt(searchParams.get("offset") ?? "0");
  const offset = Number.isNaN(offsetRaw) ? 0 : Math.max(0, offsetRaw);

  const [rows, unread, totalRow] = await Promise.all([
    db
      .select({
        id: notifications.id,
        type: notifications.type,
        recipeId: notifications.recipeId,
        commentId: notifications.commentId,
        read: notifications.read,
        createdAt: notifications.createdAt,
        actorId: notifications.actorId,
        actorName: users.name,
        actorUsername: users.username,
        actorAvatarUrl: users.avatarUrl,
      })
      .from(notifications)
      .innerJoin(users, eq(notifications.actorId, users.id))
      .where(eq(notifications.userId, session!.user.id))
      .orderBy(desc(notifications.createdAt))
      .limit(limit)
      .offset(offset),
    db
      .select({ total: count() })
      .from(notifications)
      .where(and(eq(notifications.userId, session!.user.id), eq(notifications.read, false))),
    db
      .select({ total: count() })
      .from(notifications)
      .where(eq(notifications.userId, session!.user.id)),
  ]);

  return NextResponse.json({
    notifications: rows,
    unreadCount: unread[0]?.total ?? 0,
    total: totalRow[0]?.total ?? 0,
    limit,
    offset,
  });
}
