import { auth } from "@/auth";
import { prisma } from "@/lib/prisma";

export const getWorkspaces = async () => {
  const session = await auth();

  console.log("getWorkspaces - Session:", session?.user);

  if (!session?.user?.email) {
    console.log("getWorkspaces - No session or email");
    return { documents: [], total: 0 };
  }

  // Find the user by email first
  const currentUser = await prisma.user.findUnique({
    where: { email: session.user.email },
  });

  if (!currentUser) {
    console.log("getWorkspaces - User not found:", session.user.email);
    return { documents: [], total: 0 };
  }

  console.log("getWorkspaces - Found user:", currentUser.id);

  // Find all memberships for the user
  const memberships = await prisma.member.findMany({
    where: { userId: currentUser.id },
    include: { 
      workspace: true
    },
    orderBy: {
      createdAt: 'desc'
    }
  });

  console.log("getWorkspaces - Found memberships:", memberships.length);

  if (memberships.length === 0) {
    return { documents: [], total: 0 };
  }

  // Extract workspaces from memberships and format them to match the expected structure
  // Sort by most recently updated workspace
  const workspaces = {
    documents: memberships
      .map(membership => membership.workspace)
      .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()),
    total: memberships.length
  };

  console.log("getWorkspaces - Returning workspaces:", workspaces.total);

  return workspaces;
};
