import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

interface TreeNodeWithChildren {
  id: string;
  name: string;
  nodeType: string;
  parentId: string | null;
  sortOrder: number;
  children: TreeNodeWithChildren[];
}

function buildTreeStructure(nodes: any[]): TreeNodeWithChildren[] {
  const nodeMap = new Map<string, TreeNodeWithChildren>();
  
  // Create node objects
  nodes.forEach(node => {
    nodeMap.set(node.id, {
      id: node.id,
      name: node.name,
      nodeType: node.nodeType,
      parentId: node.parentId,
      sortOrder: node.sortOrder,
      children: []
    });
  });

  // Build parent-child relationships
  const rootNodes: TreeNodeWithChildren[] = [];
  
  nodeMap.forEach(node => {
    if (node.parentId === null) {
      rootNodes.push(node);
    } else {
      const parent = nodeMap.get(node.parentId);
      if (parent) {
        parent.children.push(node);
      }
    }
  });

  // Sort children by sortOrder
  const sortChildren = (nodes: TreeNodeWithChildren[]) => {
    nodes.sort((a, b) => a.sortOrder - b.sortOrder);
    nodes.forEach(node => sortChildren(node.children));
  };

  sortChildren(rootNodes);
  return rootNodes;
}

export async function GET(
  request: NextRequest,
  context: { params: Promise<{ treeId: string }> }
) {
  try {
    const { treeId } = await context.params;
    const nodes = await prisma.treeNode.findMany({
      where: { treeId },
      select: {
        id: true,
        name: true,
        nodeType: true,
        parentId: true,
        sortOrder: true
      },
      orderBy: { sortOrder: 'asc' }
    });

    const treeStructure = buildTreeStructure(nodes);
    return NextResponse.json(treeStructure);
  } catch (error) {
    console.error('Failed to fetch tree nodes:', error);
    return NextResponse.json(
      { error: 'Failed to fetch tree nodes' }, 
      { status: 500 }
    );
  }
}