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 intake with all relations
export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  const authResult = await requireDFAuth();
  if (!authResult.authorized) return authResult.response;

  const intake = await prisma.dfIntake.findUnique({
    where: { id: params.id },
    include: {
      entities: { orderBy: { sortOrder: 'asc' } },
      visuals: { orderBy: { sortOrder: 'asc' } },
      deliverables: { orderBy: { sortOrder: 'asc' } },
      acceptanceCriteria: { orderBy: { sortOrder: 'asc' } },
      revisionLog: { orderBy: { createdAt: 'desc' }, take: 20 },
    },
  });

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

  // M4: If generation completed, include linked artifact info
  let artifacts: { id: string; type: string; path: string; version: number }[] = [];
  if (intake.generationRequestId) {
    try {
      const genReq = await prisma.generationRequest.findUnique({
        where: { id: intake.generationRequestId },
        include: { task: { include: { artifacts: { select: { id: true, type: true, path: true, version: true } } } } },
      });
      if (genReq?.task?.artifacts) {
        artifacts = genReq.task.artifacts;
      }
    } catch { /* non-fatal */ }
  }

  return NextResponse.json({ intake, artifacts });
}

// PATCH — update intake (only allowed in draft/revision states)
export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
  const authResult = await requireDFAuth();
  if (!authResult.authorized) return authResult.response;

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

  if (!['intake_draft', 'intake_revision'].includes(intake.gate)) {
    return NextResponse.json({ error: `Cannot edit intake in ${intake.gate} state. Must be in draft or revision.` }, { status: 400 });
  }

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

  const updated = await prisma.dfIntake.update({
    where: { id: params.id },
    data: {
      ...(title && { title }),
      ...(clientName !== undefined && { clientName }),
      ...(clientCompany !== undefined && { clientCompany }),
      ...(businessDomain && { businessDomain }),
      ...(problemStatement && { problemStatement }),
      ...(targetUsers && { targetUsers }),
      ...(coreWorkflows && { coreWorkflows }),
      ...(constraints && { constraints }),
      ...(integrations && { integrations }),
      ...(targetLanguage && { targetLanguage }),
      ...(targetDatabase && { targetDatabase }),
      ...(budget !== undefined && { budget }),
      ...(timeline !== undefined && { timeline }),
      ...(notes !== undefined && { notes }),
    },
    include: {
      entities: { orderBy: { sortOrder: 'asc' } },
      acceptanceCriteria: { orderBy: { sortOrder: 'asc' } },
    },
  });

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