import { redirect } from "next/navigation";

import { auth } from "@/auth";
import { prisma } from "@/lib/db";
import { KanbanBoard } from "@/components/board/kanban-board";
import type { CategoryDTO } from "@/types/board";

export default async function HomePage() {
  const session = await auth();
  if (!session?.user) redirect("/login");

  const categories = await prisma.category.findMany({
    where: { userId: session.user.id },
    orderBy: { order: "asc" },
    include: {
      groups: {
        orderBy: { order: "asc" },
        include: { todos: { orderBy: { order: "asc" } } },
      },
    },
  });

  const board: CategoryDTO[] = categories.map((category) => ({
    id: category.id,
    name: category.name,
    order: category.order,
    groups: category.groups.map((group) => ({
      id: group.id,
      title: group.title,
      color: group.color,
      order: group.order,
      noteContent: group.noteContent,
      categoryId: group.categoryId,
      todos: group.todos.map((todo) => ({
        id: todo.id,
        title: todo.title,
        details: todo.details,
        completed: todo.completed,
        order: todo.order,
        groupId: todo.groupId,
      })),
    })),
  }));

  return <KanbanBoard initialCategories={board} />;
}
