import { getSessionUser } from "@/lib/auth";
import {
  getKavenixAdminUserAuthActivityById,
  isKavenixAdminEmail,
} from "@/lib/kavenix-admin";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const NO_STORE_HEADERS = {
  "Cache-Control": "no-store, max-age=0",
};

export async function GET(
  request: Request,
  context: { params: Promise<{ userId: string }> },
) {
  const user = await getSessionUser();

  if (!user) {
    return Response.json(
      { error: "unauthorized", message: "로그인이 필요합니다." },
      { status: 401, headers: NO_STORE_HEADERS },
    );
  }

  if (!isKavenixAdminEmail(user.email)) {
    return Response.json(
      { error: "forbidden", message: "최고관리자만 조회할 수 있습니다." },
      { status: 403, headers: NO_STORE_HEADERS },
    );
  }

  const { userId: rawUserId } = await context.params;
  const userId = Number(rawUserId);

  try {
    const page = await getKavenixAdminUserAuthActivityById(
      userId,
      new URL(request.url).searchParams.get("cursor"),
    );
    return Response.json(
      { ...page, ok: true },
      { status: 200, headers: NO_STORE_HEADERS },
    );
  } catch (error) {
    const notFound =
      error instanceof Error && error.message === "kavenix-user-not-found";
    const invalidCursor =
      error instanceof Error &&
      error.message === "invalid-auth-activity-cursor";
    return Response.json(
      {
        error: notFound
          ? "user-not-found"
          : invalidCursor
            ? "invalid-cursor"
            : "activity-load-failed",
        message: notFound
          ? "사용자를 찾을 수 없습니다."
          : invalidCursor
            ? "조회 위치가 올바르지 않습니다. 창을 다시 열어주세요."
            : "접속 기록을 불러오지 못했습니다.",
      },
      {
        status: notFound ? 404 : invalidCursor ? 400 : 500,
        headers: NO_STORE_HEADERS,
      },
    );
  }
}
