import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { parseSessionCookie, loadAdminSession, touchSession } from "@/lib/auth";

export const runtime = "nodejs";

export async function GET(req: NextRequest) {
  try {
    const cookieHeader = req.headers.get("cookie");
    const sessionId = parseSessionCookie(cookieHeader);

    if (!sessionId) {
      return NextResponse.json({ user: null });
    }

    const session = await loadAdminSession(sessionId);
    if (!session) {
      return NextResponse.json({ user: null });
    }

    // 刷新活跃时间
    await touchSession(sessionId);

    return NextResponse.json({
      user: {
        id: session.userId,
        username: session.username,
        roles: session.roles,
        permissions: session.permissions,
      },
    });
  } catch (e) {
    logError("Session check error:", e);
    return NextResponse.json({ user: null });
  }
}
