export const dynamic = 'force-dynamic';

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

const GATE_TRANSITIONS: Record<string, { next: string; approvalField: string }> = {
  intake_draft: { next: 'intake_approved', approvalField: 'intakeApprovedAt' },
  intake_revision: { next: 'intake_approved', approvalField: 'intakeApprovedAt' },
  visuals_generated: { next: 'visuals_approved', approvalField: 'visualsApprovedAt' },
  visuals_revision: { next: 'visuals_approved', approvalField: 'visualsApprovedAt' },
  deliverables_defined: { next: 'deliverables_approved', approvalField: 'deliverablesApprovedAt' },
  deliverables_revision: { next: 'deliverables_approved', approvalField: 'deliverablesApprovedAt' },
};

// POST — approve current gate and advance to next
export async function POST(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 });

  const transition = GATE_TRANSITIONS[intake.gate];
  if (!transition) {
    return NextResponse.json({ error: `Cannot approve from gate: ${intake.gate}` }, { status: 400 });
  }

  const body = await req.json().catch(() => ({}));
  const approvedBy = authResult.userId || 'unknown';
  const now = new Date();

  const updateData: Record<string, unknown> = {
    gate: transition.next,
    [transition.approvalField]: now,
    [`${transition.approvalField.replace('At', 'By')}`]: approvedBy,
  };

  const updated = await prisma.dfIntake.update({
    where: { id: params.id },
    data: updateData,
    include: {
      entities: true,
      visuals: true,
      deliverables: true,
      acceptanceCriteria: true,
    },
  });

  await prisma.dfRevisionLog.create({
    data: {
      intakeId: params.id,
      gate: intake.gate,
      action: 'approved',
      changedBy: approvedBy,
      reason: body.reason || `Gate ${intake.gate} approved`,
    },
  });

  return NextResponse.json({ intake: updated, previousGate: intake.gate, newGate: transition.next });
}

// PATCH — request revision (send back to revision state)
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 });

  const body = await req.json();
  if (!body.reason) return NextResponse.json({ error: 'Revision reason is required' }, { status: 400 });

  // Map current gate to its revision state
  const revisionMap: Record<string, string> = {
    intake_draft: 'intake_revision',
    intake_approved: 'intake_revision',
    visuals_generated: 'visuals_revision',
    visuals_approved: 'visuals_revision',
    deliverables_defined: 'deliverables_revision',
    deliverables_approved: 'deliverables_revision',
  };

  const revisionGate = revisionMap[intake.gate];
  if (!revisionGate) {
    return NextResponse.json({ error: `Cannot request revision from gate: ${intake.gate}` }, { status: 400 });
  }

  const updated = await prisma.dfIntake.update({
    where: { id: params.id },
    data: { gate: revisionGate },
  });

  await prisma.dfRevisionLog.create({
    data: {
      intakeId: params.id,
      gate: intake.gate,
      action: 'revision_requested',
      changedBy: authResult.userId || 'unknown',
      reason: body.reason,
    },
  });

  return NextResponse.json({ intake: updated, previousGate: intake.gate, newGate: revisionGate });
}
