/**
 * Auto-generated by ${VOCAB.factory}
 * KnowledgeNode API Routes
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { VOCAB } from '@/lib/white-label/constants';

export const dynamic = 'force-dynamic';


// GET - List all KnowledgeNode records
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '20');
    const skip = (page - 1) * limit;

    const [items, total] = await Promise.all([
      prisma.knowledgeNode.findMany({
        skip,
        take: limit,
        orderBy: { createdAt: 'desc' },
      }),
      prisma.knowledgeNode.count(),
    ]);

    return NextResponse.json({
      data: items,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error('Error fetching KnowledgeNode:', error);
    return NextResponse.json(
      { error: 'Failed to fetch KnowledgeNode records' },
      { status: 500 }
    );
  }
}


// POST - Create a new KnowledgeNode
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // Validate required fields
    const required = ['content', 'entities', 'concepts', 'relationships', 'confidenceScore', 'sourceType', 'sourceReference', 'conflictStatus'];
    const missing = required.filter(field => !(field in body));
    if (missing.length > 0) {
      return NextResponse.json(
        { error: `Missing required fields: ${missing.join(', ')}` },
        { status: 400 }
      );
    }

    const knowledgeNode = await prisma.knowledgeNode.create({
      data: body,
    });

    return NextResponse.json(knowledgeNode, { status: 201 });
  } catch (error) {
    console.error('Error creating KnowledgeNode:', error);
    return NextResponse.json(
      { error: 'Failed to create KnowledgeNode' },
      { status: 500 }
    );
  }
}
