import { NextResponse } from 'next/server';
import { recordEvent } from '@/lib/auditDb';
import { copyToSelected, loadSession, saveSession } from '@/lib/storage';

export const runtime = 'nodejs';

export async function POST(req: Request) {
  const { sessionId, imageId, action } = (await req.json()) as {
    sessionId: string;
    imageId: string;
    action: 'select' | 'reject' | 'reset';
  };

  const session = await loadSession(sessionId);
  if (!session) return NextResponse.json({ error: 'session not found' }, { status: 404 });

  const img = session.images.find(i => i.id === imageId);
  if (!img) return NextResponse.json({ error: 'image not found' }, { status: 404 });

  if (action === 'select') {
    const newUrl = await copyToSelected(sessionId, imageId, img.url);
    img.status = 'selected';
    img.meta = { ...(img.meta ?? {}), selectedUrl: newUrl };
  } else if (action === 'reject') {
    img.status = 'rejected';
  } else {
    img.status = 'pending';
  }
  await saveSession(session);
  recordEvent({
    action: `image.${action}`,
    sessionId,
    targetType: 'image',
    targetId: imageId,
    status: 'ok',
    metadata: { selectedUrl: img.meta?.selectedUrl ?? null },
  });
  return NextResponse.json({ ok: true, image: img });
}
