import { NextRequest, NextResponse } from "next/server";
import {
  getNotifications,
  getUnreadCount,
  markRead,
  markAllRead,
  dismissNotification,
} from "@/lib/notifications";
import { requireApiAuth, handleApiError } from "@/lib/api-auth";

export async function GET(request: NextRequest) {
  try {
    const session = await requireApiAuth();
    const userId = session.user.id!;
    const { searchParams } = new URL(request.url);
    const unreadOnly = searchParams.get("unreadOnly") === "true";
    const limit = Math.min(100, parseInt(searchParams.get("limit") || "50"));

    const [notifications, unreadCount] = await Promise.all([
      getNotifications({ userId, unreadOnly, limit }),
      getUnreadCount(userId),
    ]);

    return NextResponse.json({ notifications, unreadCount });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function PUT(request: NextRequest) {
  try {
    const session = await requireApiAuth();
    const userId = session.user.id!;
    const body = await request.json().catch(() => ({}));
    const action = body.action as string;

    if (action === "mark_read" && body.id) {
      await markRead(body.id, userId);
    } else if (action === "mark_all_read") {
      await markAllRead(userId);
    } else if (action === "dismiss" && body.id) {
      await dismissNotification(body.id, userId);
    } else {
      return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    }

    const unreadCount = await getUnreadCount(userId);
    return NextResponse.json({ ok: true, unreadCount });
  } catch (error) {
    return handleApiError(error);
  }
}
