import { getRuntimeEnv } from "../../../lib/runtime-env";
import { runInBackground } from "../../../lib/background";

const env = getRuntimeEnv();
import { backfillAccountProfiles } from "../../../lib/account-enrichment-service";
import { runDueScheduledCollections } from "../../../lib/collection-service";
import {
  resolveCollectionMcpConfig,
  type CollectionMcpBindings,
} from "../../../lib/mcp-collection-client";
import {
  ensureSchema,
  getDashboardData,
  getRawDb,
  seedIfEmpty,
} from "../../../lib/mvp-db";
import { authForbidden, getRequestPrincipal } from "../../../lib/user-auth";

export async function GET(request: Request) {
  const principal = await getRequestPrincipal(request);
  if (!principal) return authForbidden();
  try {
    await ensureSchema();
    await seedIfEmpty();
    const db = getRawDb();
    const mcpConfig = resolveCollectionMcpConfig(
      env as unknown as CollectionMcpBindings,
    );
    const collectionCatchup = runDueScheduledCollections(
      db,
      Date.now(),
      mcpConfig,
      "catchup",
    ).catch((error) => {
      console.error(
        "KOC collection catchup failed",
        error instanceof Error ? error.message : "unknown error",
      );
    });
    const accountBackfill = backfillAccountProfiles(
      db,
      mcpConfig,
      10,
    )
      .then((result) => {
        console.info("KOC account backfill completed", result);
      })
      .catch((error) => {
        console.error(
          "KOC account backfill failed",
          error instanceof Error ? error.message : "unknown error",
        );
      });
    const catchup = Promise.all([
      collectionCatchup,
      accountBackfill,
    ]);
    runInBackground(catchup, "bootstrap catchup");
    const dashboard = await getDashboardData();
    return Response.json(
      principal.kind === "user" && principal.user.role === "user"
        ? { ...dashboard, accounts: [] }
        : dashboard,
    );
  } catch (error) {
    return Response.json(
      { error: error instanceof Error ? error.message : "加载失败" },
      { status: 500 },
    );
  }
}
