import { NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { documents } from '@/lib/db/schema';
import type { DocumentSigner } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';

// PATCH /api/documents/[id] — partial update (signers, name, etc.)
export async function PATCH(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth();
  if (!session) return new Response('Unauthorized', { status: 401 });

  const { id } = await params;
  const body = await req.json() as { signers?: DocumentSigner[] };

  const doc = await db.query.documents.findFirst({ where: eq(documents.id, id) });
  if (!doc) return NextResponse.json({ error: 'Not found' }, { status: 404 });

  const updates: Partial<typeof documents.$inferInsert> = {};
  if (body.signers !== undefined) updates.signers = body.signers;

  if (Object.keys(updates).length === 0) {
    return NextResponse.json({ ok: true });
  }

  const [updated] = await db
    .update(documents)
    .set(updates)
    .where(eq(documents.id, id))
    .returning();

  return NextResponse.json(updated);
}
