import { NextRequest, NextResponse } from "next/server";
import { db, isDatabaseAvailable } from "@/lib/db";
import { ensureDatabaseInitialized } from "@/lib/db/init";
import { getAdminUser } from "@/lib/auth/admin";
import { requireCsrf } from "@/lib/auth/csrf";
import { clientIp } from "@/lib/auth/rateLimit";
import {
  logSecurityEventAsync,
  SecurityEventType,
} from "@/lib/auth/securityEvents";
import { waitlist } from "@/lib/schema/db";
import { desc, eq } from "drizzle-orm";

export const runtime = "nodejs";

export async function GET(req: NextRequest) {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

  logSecurityEventAsync({
    type: SecurityEventType.ADMIN_ACTION,
    userId: admin.id,
    email: admin.email,
    ip: clientIp(req),
    userAgent: req.headers.get("user-agent"),
    metadata: { route: "/api/admin/waitlist", method: "GET" },
  });

  if (!(await isDatabaseAvailable())) {
    return NextResponse.json({ error: 'Database unavailable' }, { status: 503 });
  }
  await ensureDatabaseInitialized();

  try {
    const list = await db.select()
      .from(waitlist)
      .orderBy(desc(waitlist.createdAt));

    return NextResponse.json({ waitlist: list });
  } catch (error) {
    console.error("Admin waitlist GET error:", error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

export async function DELETE(req: NextRequest) {
  const csrfBlocked = requireCsrf(req);
  if (csrfBlocked) return csrfBlocked;

  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

  logSecurityEventAsync({
    type: SecurityEventType.ADMIN_ACTION,
    userId: admin.id,
    email: admin.email,
    ip: clientIp(req),
    userAgent: req.headers.get("user-agent"),
    metadata: { route: "/api/admin/waitlist", method: "DELETE", id: req.nextUrl.searchParams.get("id") ?? undefined },
  });

  const id = req.nextUrl.searchParams.get("id");
  if (!id) return NextResponse.json({ error: 'Missing id' }, { status: 400 });

  if (!(await isDatabaseAvailable())) {
    return NextResponse.json({ error: 'Database unavailable' }, { status: 503 });
  }
  await ensureDatabaseInitialized();

  try {
    await db.delete(waitlist).where(eq(waitlist.id, id));
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Admin waitlist DELETE error:", error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
