import { NextRequest, NextResponse } from "next/server";
import {
  getOnlinePlatformSessions,
  kickPlatformSession,
  PlatformSessionInfo,
} 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 getOnlinePlatformSessions();
    // Log for debugging if sessions are empty
    if (sessions.length === 0) {
      console.log("[platform-sessions] No sessions found via Redis SCAN session:user_uid:*");
    }
    return NextResponse.json({ sessions });
  } catch (e) {
    console.error("Get platform 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 ok = await kickPlatformSession(sessionId);

    const { userId, username } = getAuthInfo(req);
    await createAuditLog({
      userId,
      username,
      action: "delete",
      resource: "platform_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 platform session error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
