import { NextRequest, NextResponse } from "next/server";
import { getOnlineSessions } from "@/lib/redis";
import { createAuditLog } from "@/lib/log";

function getAuthInfo(req: NextRequest) {
  return {
    userId: parseInt(req.headers.get("x-admin-user-id") || "0", 10),
    username: req.headers.get("x-admin-username") || "unknown",
  };
}

export async function GET() {
  try {
    const sessions = await getOnlineSessions();
    return NextResponse.json({ sessions });
  } catch (e) {
    console.error("Get sessions error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

export async function DELETE(req: NextRequest) {
  try {
    const body = await req.json() as { sessionId?: string };
    const { sessionId } = body;

    if (!sessionId) {
      return NextResponse.json({ error: "sessionId 不能为空" }, { status: 400 });
    }

    const { kickSession } = await import("@/lib/redis");
    const ok = await kickSession(sessionId);

    const { userId, username } = getAuthInfo(req);
    await createAuditLog({
      userId,
      username,
      action: "delete",
      resource: "admin_session",
      resourceId: sessionId.slice(0, 8) + "...",
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

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