import { NextResponse } from "next/server";
import { eq } from "drizzle-orm";
import { getServerSession } from "next-auth";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { db } from "@/app/db/db";
import { getPortfolios } from "@/app/home/utils";
import {
  userPortfolioConfig,
  userPortfolioFolders,
} from "@/app/db/schema/user_portfolio_config";

// Everything the home page renders, flat: the client groups via
// groupPortfoliosForHome so optimistic mutations can re-group locally.
export async function GET() {
  try {
    const session = await getServerSession(AuthOptions);
    if (!session?.user?.dbId) {
      return NextResponse.json({ error: "Unauthenticated" }, { status: 401 });
    }
    const userId = session.user.dbId;

    const [portfolios, configs, folders] = await Promise.all([
      getPortfolios(userId),
      db
        .select({
          portfolioId: userPortfolioConfig.portfolioId,
          folderId: userPortfolioConfig.folderId,
          starredAt: userPortfolioConfig.starredAt,
        })
        .from(userPortfolioConfig)
        .where(eq(userPortfolioConfig.userId, userId)),
      db
        .select({
          id: userPortfolioFolders.id,
          name: userPortfolioFolders.name,
          position: userPortfolioFolders.position,
        })
        .from(userPortfolioFolders)
        .where(eq(userPortfolioFolders.userId, userId)),
    ]);

    const body = { portfolios, configs, folders };

    // bigint isn't JSON-serialisable; ids cross the wire as strings.
    return new NextResponse(
      JSON.stringify(body, (_key, value) =>
        typeof value === "bigint" ? value.toString() : value,
      ),
      { status: 200, headers: { "content-type": "application/json" } },
    );
  } catch (err) {
    console.error("Error loading portfolio home:", err);
    return NextResponse.json({ error: "Server error" }, { status: 500 });
  }
}
