import { redirect } from "next/navigation";

import { getCurrent } from "@/features/auth/queries";
import { getWorkspaces } from "@/features/workspaces/queries";

export const dynamic = 'force-dynamic';

export default async function Home() {
  const user = await getCurrent();

  if (!user) {
    redirect("/sign-in");
  }

  const workspaces = await getWorkspaces();

  // Debug logging to see what's happening
  console.log("Homepage - User:", user?.id);
  console.log("Homepage - Workspaces:", workspaces);

  if (!workspaces || workspaces.total === 0 || !workspaces.documents || workspaces.documents.length === 0) {
    redirect("/no-workspaces");
  } else {
    // Sort workspaces by most recently updated and pick the latest one
    const sortedWorkspaces = workspaces.documents.sort((a: { updatedAt: string | number | Date; }, b: { updatedAt: string | number | Date; }) => 
      new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
    );
    
    redirect(`/workspaces/${sortedWorkspaces[0].id}`);
  }
}
