import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { users } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';

export async function GET() {
  const session = await auth();
  if (!session?.user?.id) return new Response('Unauthorized', { status: 401 });

  const user = await db.query.users.findFirst({
    where: eq(users.id, session.user.id),
    columns: { agentSignatureData: true },
  });

  return Response.json({ agentSignatureData: user?.agentSignatureData ?? null });
}

export async function PUT(req: Request) {
  const session = await auth();
  if (!session?.user?.id) return new Response('Unauthorized', { status: 401 });

  const { dataURL } = await req.json() as { dataURL: string };

  if (!dataURL || !dataURL.startsWith('data:image/png;base64,')) {
    return Response.json({ error: 'Invalid signature data' }, { status: 422 });
  }
  if (dataURL.length > 50_000) {
    return Response.json({ error: 'Signature data too large' }, { status: 422 });
  }

  await db.update(users)
    .set({ agentSignatureData: dataURL })
    .where(eq(users.id, session.user.id));

  return Response.json({ ok: true });
}
