export const dynamic = 'force-dynamic';

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

/**
 * PATCH — update individual visual status (approve / request revision / update feedback)
 */
export async function PATCH(
  req: NextRequest,
  { params }: { params: { id: string; visualId: string } }
) {
  const authResult = await requireDFAuth();
  if (!authResult.authorized) return authResult.response;

  const visual = await prisma.dfVisual.findUnique({
    where: { id: params.visualId },
    include: { intake: true },
  });

  if (!visual || visual.intakeId !== params.id) {
    return NextResponse.json({ error: 'Visual not found' }, { status: 404 });
  }

  const body = await req.json();
  const { action, feedback, content } = body;

  // Handle content-only update (live-edit)
  if (content !== undefined && !action) {
    if (typeof content !== 'string' || !content.trim()) {
      return NextResponse.json({ error: 'content must be a non-empty string' }, { status: 400 });
    }
    const updated = await prisma.dfVisual.update({
      where: { id: params.visualId },
      data: { content: content.trim() },
    });
    await prisma.dfRevisionLog.create({
      data: {
        intakeId: params.id,
        gate: visual.intake.gate,
        action: 'visual_content_edit',
        changedBy: authResult.userId || 'unknown',
        reason: `${visual.title}: Mermaid source edited`,
      },
    });
    return NextResponse.json({ visual: updated });
  }

  if (!action || !['approve', 'request_revision'].includes(action)) {
    return NextResponse.json(
      { error: 'action must be "approve" or "request_revision"' },
      { status: 400 }
    );
  }

  if (action === 'request_revision' && !feedback?.trim()) {
    return NextResponse.json(
      { error: 'feedback is required when requesting revision' },
      { status: 400 }
    );
  }

  const newStatus = action === 'approve' ? 'approved' : 'revision_requested';

  const updated = await prisma.dfVisual.update({
    where: { id: params.visualId },
    data: {
      status: newStatus,
      feedback: action === 'request_revision' ? feedback : visual.feedback,
    },
  });

  // Log the action in revision log
  await prisma.dfRevisionLog.create({
    data: {
      intakeId: params.id,
      gate: visual.intake.gate,
      action: `visual_${action}`,
      changedBy: authResult.userId || 'unknown',
      reason: `${visual.title} (${visual.type}): ${action === 'approve' ? 'Approved' : feedback}`,
    },
  });

  // Check if ALL visuals are now approved — if so, auto-advance gate hint
  const allVisuals = await prisma.dfVisual.findMany({
    where: { intakeId: params.id },
  });
  const allApproved = allVisuals.length > 0 && allVisuals.every(v => v.status === 'approved');

  return NextResponse.json({
    visual: updated,
    allVisualsApproved: allApproved,
    hint: allApproved ? 'All visuals approved. You can now approve the visuals gate.' : undefined,
  });
}
