import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, recipes, users, userFollows, eq, desc, inArray } from "@epicure/db";
import { getPublicUrl } from "@/lib/storage";
import { FeedPageContent } from "@/components/feed/feed-page-content";

export const metadata: Metadata = {};

export default async function FeedPage() {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) return null;

  const followedRows = await db
    .select({ followingId: userFollows.followingId })
    .from(userFollows)
    .where(eq(userFollows.followerId, session.user.id));

  const followedIds = followedRows.map((r) => r.followingId);

  if (followedIds.length === 0) {
    return <FeedPageContent followedCount={0} feedRecipes={[]} />;
  }

  const feedRecipes = await db
    .select({
      id: recipes.id,
      title: recipes.title,
      description: recipes.description,
      baseServings: recipes.baseServings,
      prepMins: recipes.prepMins,
      cookMins: recipes.cookMins,
      difficulty: recipes.difficulty,
      visibility: recipes.visibility,
      aiGenerated: recipes.aiGenerated,
      createdAt: recipes.createdAt,
      authorId: recipes.authorId,
      authorName: users.name,
      authorUsername: users.username,
      authorAvatarUrl: users.avatarUrl,
    })
    .from(recipes)
    .innerJoin(users, eq(recipes.authorId, users.id))
    .where(inArray(recipes.authorId, followedIds))
    .orderBy(desc(recipes.createdAt))
    .limit(40);

  return (
    <FeedPageContent
      followedCount={followedIds.length}
      feedRecipes={feedRecipes.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() }))}
    />
  );
}
