import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { deleteApiToken } from "@/lib/api-token";
import { createAuditLog } from "@/lib/log";

export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const tokenId = parseInt(id, 10);
    if (isNaN(tokenId)) {
      return NextResponse.json({ error: "无效的 Token ID" }, { status: 400 });
    }

    await deleteApiToken(tokenId);

    const adminUserId = parseInt(req.headers.get("x-admin-user-id") || "0", 10);
    const adminUsername = req.headers.get("x-admin-username") || "unknown";
    await createAuditLog({
      userId: adminUserId,
      username: adminUsername,
      action: "delete",
      resource: "admin_api_token",
      resourceId: id,
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

    return NextResponse.json({ success: true });
  } catch (e) {
    logError("Delete token error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
