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 — list all intakes
export async function GET(req: NextRequest) {
  const authResult = await requireDFAuth();
  if (!authResult.authorized) return authResult.response;

  const intakes = await prisma.dfIntake.findMany({
    orderBy: { createdAt: 'desc' },
    include: {
      entities: { orderBy: { sortOrder: 'asc' } },
      visuals: { orderBy: { sortOrder: 'asc' } },
      deliverables: { orderBy: { sortOrder: 'asc' } },
      acceptanceCriteria: { orderBy: { sortOrder: 'asc' } },
      _count: { select: { revisionLog: true } },
    },
  });

  return NextResponse.json({ intakes });
}

// POST — create new intake
export async function POST(req: NextRequest) {
  const authResult = await requireDFAuth();
  if (!authResult.authorized) return authResult.response;

  const body = await req.json();
  const { title, clientName, clientCompany, businessDomain, problemStatement,
    targetUsers, coreWorkflows, constraints, integrations,
    targetLanguage, targetDatabase, budget, timeline, notes, entities, acceptanceCriteria } = body;

  if (!title || !businessDomain || !problemStatement) {
    return NextResponse.json({ error: 'title, businessDomain, and problemStatement are required' }, { status: 400 });
  }

  const intake = await prisma.dfIntake.create({
    data: {
      title,
      clientName: clientName || null,
      clientCompany: clientCompany || null,
      businessDomain,
      problemStatement,
      targetUsers: targetUsers || [],
      coreWorkflows: coreWorkflows || [],
      constraints: constraints || [],
      integrations: integrations || [],
      targetLanguage: targetLanguage || 'typescript-react',
      targetDatabase: targetDatabase || 'postgresql',
      budget: budget || null,
      timeline: timeline || null,
      notes: notes || null,
      gate: 'intake_draft',
      createdBy: authResult.userId || 'unknown',
      entities: entities ? {
        create: entities.map((e: { name: string; description?: string; fields?: unknown[]; relationships?: unknown[]; isCore?: boolean }, i: number) => ({
          name: e.name,
          description: e.description || null,
          fields: e.fields || [],
          relationships: e.relationships || [],
          isCore: e.isCore !== false,
          sortOrder: i,
        })),
      } : undefined,
      acceptanceCriteria: acceptanceCriteria ? {
        create: acceptanceCriteria.map((c: { description: string; category?: string; priority?: string }, i: number) => ({
          description: c.description,
          category: c.category || 'functional',
          priority: c.priority || 'must',
          sortOrder: i,
        })),
      } : undefined,
    },
    include: {
      entities: true,
      acceptanceCriteria: true,
    },
  });

  // Log the creation
  await prisma.dfRevisionLog.create({
    data: {
      intakeId: intake.id,
      gate: 'intake_draft',
      action: 'created',
      changedBy: authResult.userId || 'unknown',
      reason: 'Initial intake created',
    },
  });

  return NextResponse.json({ intake }, { status: 201 });
}
