/**
 * Auto-generated by ${VOCAB.factory}
 * WorkflowStep 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 WorkflowStep 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.workflowStep.findMany({
        skip,
        take: limit,
        orderBy: { createdAt: 'desc' },
      }),
      prisma.workflowStep.count(),
    ]);

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


// POST - Create a new WorkflowStep
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // Validate required fields
    const required = ['workflowId', 'name', 'type', 'config', 'inputs', 'outputs', 'order', 'branchCondition', 'workflowRuntimeEngineId', 'workflowRuntimeEngine', 'agentId', 'agent'];
    const missing = required.filter(field => !(field in body));
    if (missing.length > 0) {
      return NextResponse.json(
        { error: `Missing required fields: ${missing.join(', ')}` },
        { status: 400 }
      );
    }

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

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