export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { requireDFAuth } from '@/lib/dark-factory/auth-guard';

// GET — single workflow with full step details
export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  const authResult = await requireDFAuth();
  if (!authResult.authorized) return authResult.response;

  const workflow = await prisma.workflow.findUnique({
    where: { id: params.id },
    include: {
      workflowSteps: { orderBy: { order: 'asc' } },
      WorkflowExecution: {
        orderBy: { startedAt: 'desc' },
        take: 5,
      },
    },
  });

  if (!workflow) return NextResponse.json({ error: 'Workflow not found' }, { status: 404 });
  return NextResponse.json({ workflow });
}

// PATCH — update workflow steps (visual editor saves)
export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
  const authResult = await requireDFAuth();
  if (!authResult.authorized) return authResult.response;

  const workflow = await prisma.workflow.findUnique({ where: { id: params.id } });
  if (!workflow) return NextResponse.json({ error: 'Workflow not found' }, { status: 404 });

  const body = await req.json();
  const { steps, name, description, status } = body;

  // Update workflow metadata if provided
  if (name || description || status) {
    await prisma.workflow.update({
      where: { id: params.id },
      data: {
        ...(name && { name }),
        ...(description !== undefined && { description }),
        ...(status && { status }),
      },
    });
  }

  // If steps array provided, replace all steps
  if (Array.isArray(steps)) {
    // Delete old steps
    await prisma.workflowStep.deleteMany({ where: { workflowId: params.id } });
    // Create new steps
    for (let i = 0; i < steps.length; i++) {
      const s = steps[i];
      await prisma.workflowStep.create({
        data: {
          workflowId: params.id,
          name: s.name || `Step ${i + 1}`,
          description: s.description || null,
          order: i,
          action: s.action || {},
          agentId: s.agentId || null,
          conditions: s.conditions || null,
          nextSteps: s.nextSteps || null,
          timeout: s.timeout || null,
          retryConfig: s.retryConfig || null,
        },
      });
    }
  }

  const updated = await prisma.workflow.findUnique({
    where: { id: params.id },
    include: { workflowSteps: { orderBy: { order: 'asc' } } },
  });

  return NextResponse.json({ workflow: updated });
}
