export const dynamic = 'force-dynamic';

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

// POST — clone an intake (creates a copy in draft state)
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
  const authResult = await requireDFAuth();
  if (!authResult.authorized) return authResult.response;

  const source = await prisma.dfIntake.findUnique({
    where: { id: params.id },
    include: {
      entities: { orderBy: { sortOrder: 'asc' } },
      acceptanceCriteria: { orderBy: { sortOrder: 'asc' } },
    },
  });

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

  const body = await req.json().catch(() => ({}));
  const newTitle = body.title || `${source.title} (Copy)`;

  const clone = await prisma.dfIntake.create({
    data: {
      title: newTitle,
      clientName: source.clientName,
      clientCompany: source.clientCompany,
      businessDomain: source.businessDomain,
      problemStatement: source.problemStatement,
      targetUsers: source.targetUsers as Prisma.InputJsonValue,
      coreWorkflows: source.coreWorkflows as Prisma.InputJsonValue,
      constraints: source.constraints as Prisma.InputJsonValue,
      integrations: source.integrations as Prisma.InputJsonValue,
      targetLanguage: source.targetLanguage,
      targetDatabase: source.targetDatabase,
      budget: source.budget,
      timeline: source.timeline,
      notes: source.notes,
      gate: 'intake_draft',
      createdBy: authResult.userId || 'unknown',
      entities: {
        create: source.entities.map((e, i) => ({
          name: e.name,
          description: e.description,
          fields: e.fields as Prisma.InputJsonValue,
          relationships: e.relationships as Prisma.InputJsonValue,
          isCore: e.isCore,
          sortOrder: i,
        })),
      },
      acceptanceCriteria: {
        create: source.acceptanceCriteria.map((c, i) => ({
          description: c.description,
          category: c.category,
          priority: c.priority,
          sortOrder: i,
        })),
      },
    },
    include: { entities: true, acceptanceCriteria: true },
  });

  await prisma.dfRevisionLog.create({
    data: {
      intakeId: clone.id,
      gate: 'intake_draft',
      action: 'created',
      changedBy: authResult.userId || 'unknown',
      reason: `Cloned from "${source.title}" (${source.id})`,
    },
  });

  return NextResponse.json({ intake: clone, sourceId: source.id }, { status: 201 });
}
