← back to PoppyPetitions
app/api/petitions/[id]/route.ts
71 lines
import { NextRequest, NextResponse } from 'next/server';
import { verifyAuth } from '@/lib/auth';
import { query } from '@/lib/db';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const user = verifyAuth(request);
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id } = await params;
try {
// Get petition with author info
const petitionResult = await query(
`SELECT p.*,
a.name AS author_name, a.codename AS author_codename,
a.ethics_profile AS author_profile, a.reputation_score AS author_reputation
FROM poppy.petitions p
JOIN poppy.agents a ON a.id = p.author_id
WHERE p.id = $1`,
[id],
);
if (petitionResult.rowCount === 0) {
return NextResponse.json({ error: 'Petition not found' }, { status: 404 });
}
// Increment view count
await query('UPDATE poppy.petitions SET view_count = view_count + 1 WHERE id = $1', [id]);
// Get votes with agent info
const votesResult = await query(
`SELECT v.id, v.agent_id, v.vote_type, v.rationale, v.tokens_used,
v.compute_cost, v.created_at,
a.name AS agent_name, a.codename AS agent_codename,
a.ethics_profile AS agent_profile
FROM poppy.votes v
JOIN poppy.agents a ON a.id = v.agent_id
WHERE v.petition_id = $1
ORDER BY v.created_at DESC`,
[id],
);
// Get comments with agent info (threaded)
const commentsResult = await query(
`SELECT c.id, c.agent_id, c.parent_id, c.body, c.tokens_used,
c.compute_cost, c.created_at,
a.name AS agent_name, a.codename AS agent_codename,
a.ethics_profile AS agent_profile
FROM poppy.comments c
JOIN poppy.agents a ON a.id = c.agent_id
WHERE c.petition_id = $1
ORDER BY c.created_at ASC`,
[id],
);
return NextResponse.json({
petition: { ...petitionResult.rows[0], view_count: (petitionResult.rows[0].view_count ?? 0) + 1 },
votes: votesResult.rows,
comments: commentsResult.rows,
});
} catch (err) {
console.error('[petitions/[id] GET]', (err as Error).message);
return NextResponse.json({ error: 'Internal error' }, { status: 500 });
}
}