import { search } from '../../../../lib/audit-search.js';
import { requireSession, requireFreshMembership } from '@/lib/auth.js';
import { assertArtifactAccess } from '@/lib/authz.js';
export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';
export async function GET(request) {
  let session;
  try {
    session = await requireSession(request);
    await requireFreshMembership(session, session.org_id);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }
  try {
    const u = new URL(request.url);
    const params = Object.fromEntries(u.searchParams.entries());
    const targetType = params.action_target_type || null;
    const targetId = params.action_target_id || null;
    if (targetId && !targetType) {
      return Response.json({ error: 'action_target_type_required' }, { status: 400 });
    }
    if (targetType === 'artifact' && !targetId) {
      return Response.json({ error: 'action_target_id_required' }, { status: 400 });
    }
    if (targetId && targetType === 'artifact') {
      await assertArtifactAccess(targetId, session, 'read', request);
    }
    // P1-6: Scope results to the caller's org — prevents cross-tenant access.
    // Caller-supplied org_id is overridden by session.org_id.
    if (session.org_id) {
      params.org_id = session.org_id;
    }
    return Response.json(search(params));
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    console.error('GET /api/audit/search error:', err);
    return Response.json({ error: 'search failed' }, { status: 500 });
  }
}
