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

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

export const dynamic = 'force-dynamic';


// GET - List all WorkflowExecution 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.workflowExecution.findMany({
        skip,
        take: limit,
        orderBy: { startedAt: 'desc' } as const,
      }),
      prisma.workflowExecution.count(),
    ]);

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


// POST - Create a new WorkflowExecution
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // Validate required fields
    const required = ['workflowId', 'status', 'currentStepIndex', 'contextData', 'startedAt', 'completedAt', 'workflowId', 'workflow'];
    const missing = required.filter(field => !(field in body));
    if (missing.length > 0) {
      return NextResponse.json(
        { error: `Missing required fields: ${missing.join(', ')}` },
        { status: 400 }
      );
    }

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

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