import { prisma } from "@/lib/db";
import { redirect } from "next/navigation";
import PortalClient from "./PortalClient";

// Force dynamic rendering - this page needs database access
export const dynamic = 'force-dynamic';

export default async function PortalPage() {
    const organization = await prisma.organization.findFirst();

    if (!organization) {
        redirect("/setup");
    }

    // Get all public root folders (projects)
    const publicFolders = await prisma.folder.findMany({
        where: {
            organizationId: organization.id,
            parentId: null,
            isPublished: true,
        },
        orderBy: { createdAt: "desc" },
        include: {
            _count: {
                select: {
                    documents: {
                        where: { isPublished: true }
                    },
                    children: {
                        where: { isPublished: true }
                    }
                }
            }
        }
    });

    return (
        <PortalClient
            organization={{
                name: organization.name,
                logoUrl: organization.logoUrl,
                primaryColor: organization.primaryColor,
            }}
            folders={publicFolders.map((f: any) => ({
                id: f.id,
                name: f.name,
                description: f.description,
                color: f.color,
                imageUrl: f.imageUrl,
                documentsCount: f._count.documents,
                foldersCount: f._count.children,
                createdAt: f.createdAt,
            }))}
        />
    );
}
