import { NextRequest, NextResponse } from "next/server";

const CSMS_INTERNAL_URL =
  process.env.CSMS_INTERNAL_URL ?? process.env.NEXT_PUBLIC_CSMS_URL ?? "http://localhost:3001";

/** 检查 CSMS 是否已完成初始化（有用户存在）。 */
async function isInitialized(): Promise<boolean> {
  try {
    const res = await fetch(`${CSMS_INTERNAL_URL}/api/setup`, {
      method: "GET",
      headers: { "Content-Type": "application/json" },
      signal: AbortSignal.timeout(3000),
    });
    if (!res.ok) return true; // 出错时放行，不阻止访问
    const data = (await res.json()) as { initialized: boolean };
    return data.initialized;
  } catch {
    // 无法连接 CSMS 时放行，不强制跳转
    return true;
  }
}

export async function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // /setup 页面：已初始化则跳转登录
  if (pathname === "/setup") {
    if (await isInitialized()) {
      return NextResponse.redirect(new URL("/login", request.url));
    }
    return NextResponse.next();
  }

  // /dashboard 路由：检查 session，未登录跳转 /login
  if (pathname.startsWith("/dashboard")) {
    if (!(await isInitialized())) {
      return NextResponse.redirect(new URL("/setup", request.url));
    }

    const sessionCookie =
      request.cookies.get("helios.session_token") ??
      request.cookies.get("__Secure-helios.session_token");

    if (!sessionCookie) {
      const loginUrl = new URL("/login", request.url);
      const fromPath = request.nextUrl.search ? pathname + request.nextUrl.search : pathname;
      loginUrl.searchParams.set("from", fromPath);
      return NextResponse.redirect(loginUrl);
    }

    return NextResponse.next();
  }

  // /login 路由：未初始化则跳转 /setup
  if (pathname === "/login") {
    if (!(await isInitialized())) {
      return NextResponse.redirect(new URL("/setup", request.url));
    }
    return NextResponse.next();
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/setup", "/login", "/dashboard/:path*"],
};
