import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { logger } from "@/lib/logger";
import { checkAlerts, acknowledgeAlert } from "@/lib/token/alerts";

/**
 * GET /api/token/alerts — Return all active alerts for the authenticated user.
 *
 * Response: { alerts: TokenAlert[], criticalCount: number, warningCount: number }
 */
export async function GET() {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const alerts = await checkAlerts(session.user.id);

    const criticalCount = alerts.filter((a) => a.severity === "critical").length;
    const warningCount = alerts.filter((a) => a.severity === "warning").length;

    return NextResponse.json({ alerts, criticalCount, warningCount });
  } catch (err) {
    logger.error({ err, action: "token_alerts_get_error" }, "Failed to check alerts");
    return NextResponse.json(
      { error: "Failed to check alerts" },
      { status: 500 },
    );
  }
}

/**
 * POST /api/token/alerts — Acknowledge an alert.
 *
 * Body: { alertId: string }
 * Response: { acknowledged: true }
 */
export async function POST(req: NextRequest) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await req.json();
    const { alertId } = body;

    if (!alertId || typeof alertId !== "string") {
      return NextResponse.json({ error: "alertId is required" }, { status: 400 });
    }

    acknowledgeAlert(session.user.id, alertId);

    logger.info(
      { action: "token_alert_ack", user_id: session.user.id, alert_id: alertId },
      "Alert acknowledged",
    );

    return NextResponse.json({ acknowledged: true });
  } catch (err) {
    logger.error({ err, action: "token_alerts_post_error" }, "Failed to acknowledge alert");
    return NextResponse.json(
      { error: "Failed to acknowledge alert" },
      { status: 500 },
    );
  }
}
