import { NextRequest, NextResponse } from "next/server";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, users, recipes, userFollows, eq, and, count } from "@epicure/db";

type Params = { params: Promise<{ username: string }> };

export async function GET(req: NextRequest, { params }: Params) {
  const { username } = await params;

  const user = await db.query.users.findFirst({ where: eq(users.username, username) });
  if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const [followerCountRow, followingCountRow, recipeCountRow] = await Promise.all([
    db
      .select({ count: count() })
      .from(userFollows)
      .where(eq(userFollows.followingId, user.id)),
    db
      .select({ count: count() })
      .from(userFollows)
      .where(eq(userFollows.followerId, user.id)),
    db
      .select({ count: count() })
      .from(recipes)
      .where(and(eq(recipes.authorId, user.id), eq(recipes.visibility, "public"))),
  ]);

  let isFollowing = false;
  try {
    const session = await auth.api.getSession({ headers: await headers() });
    if (session && session.user.id !== user.id) {
      const followRow = await db.query.userFollows.findFirst({
        where: and(
          eq(userFollows.followerId, session.user.id),
          eq(userFollows.followingId, user.id),
        ),
      });
      isFollowing = !!followRow;
    }
  } catch {
    // unauthenticated — isFollowing stays false
  }

  return NextResponse.json({
    id: user.id,
    name: user.name,
    username: user.username,
    avatarUrl: user.avatarUrl,
    bio: user.bio,
    createdAt: user.createdAt,
    followerCount: followerCountRow[0]?.count ?? 0,
    followingCount: followingCountRow[0]?.count ?? 0,
    recipeCount: recipeCountRow[0]?.count ?? 0,
    isFollowing,
  });
}
