// app/dashboard/page.tsx
import { redirect } from "next/navigation"
import { getServerSession } from "next-auth"
import { authOptions } from "@/lib/auth/config"
import { prisma } from "@/lib/prisma"

export default async function DashboardPage() {
  const session = await getServerSession(authOptions)

  if (!session) {
    redirect("/login")
  }

  // Buscar workspaces do usuário
  const user = await prisma.user.findUnique({
    where: { id: session.user.id },
    include: {
      workspacesAsEmployee: {
        where: { status: "ACTIVE" },
        include: {
          manager: { select: { name: true, avatar: true } }
        }
      },
      workspacesAsManager: {
        where: { status: "ACTIVE" },
        include: {
          employee: { select: { name: true, avatar: true } }
        }
      }
    }
  })

  // Se tiver apenas 1 workspace, redireciona diretamente
  const allWorkspaces = [
    ...(user?.workspacesAsEmployee || []),
    ...(user?.workspacesAsManager || [])
  ]

  if (allWorkspaces.length === 1) {
    redirect(`/workspace/${allWorkspaces[0].slug}`)
  }

  // Se não tiver workspaces, redireciona para criar/aceitar convite
  if (allWorkspaces.length === 0) {
    redirect("/onboarding")
  }

  // Lista todos os workspaces
  redirect("/workspaces")
}

