import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { createClient } from '@/lib/auth/server';
import { isMockDocument } from '@/lib/cortex/mock-data/noshow';

const DispatchSchema = z.object({
  documentId: z.string().min(1),
  finalContent: z.string().min(1, 'Definitieve inhoud is verplicht'),
});

export async function PATCH(request: NextRequest) {
  const supabase = await createClient();
  const { data: { user }, error: authError } = await supabase.auth.getUser();
  if (authError || !user) {
    return NextResponse.json({ error: 'Niet geautoriseerd' }, { status: 401 });
  }

  let body: z.infer<typeof DispatchSchema>;
  try {
    body = DispatchSchema.parse(await request.json());
  } catch {
    return NextResponse.json({ error: 'Ongeldige invoer' }, { status: 400 });
  }

  const { documentId, finalContent } = body;

  // Mock path — demo flow
  if (isMockDocument(documentId)) {
    return NextResponse.json({
      success: true,
      documentId,
      newStatus: 'ready_for_dispatch',
      message: 'Brief verzendklaar gemaakt (demo)',
    });
  }

  // Productie path
  const { error } = await supabase
    .from('reports')
    .update({
      status: 'ready_for_dispatch',
      structured_data: { content: finalContent },
      updated_at: new Date().toISOString(),
    })
    .eq('id', documentId)
    .eq('user_id', user.id);

  if (error) {
    console.error('[noshow/dispatch] DB error:', error);
    return NextResponse.json({ error: 'Opslaan mislukt' }, { status: 500 });
  }

  return NextResponse.json({ success: true, documentId, newStatus: 'ready_for_dispatch' });
}
