← back to Norma
app/api/library/[id]/route.ts
134 lines
import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { requireRole } from '@/lib/require-role';
import { auditLog } from '@/lib/audit';
import { getOrgId } from '@/lib/orgId';
type RouteContext = { params: Promise<{ id: string }> };
/**
* GET /api/library/[id]
* Return a single library item.
*/
export async function GET(request: NextRequest, context: RouteContext) {
const auth = requireRole(request, 'admin', 'staff');
if (auth instanceof NextResponse) return auth;
const { id } = await context.params;
try {
const orgId = auth.role === 'admin' ? getOrgId(request) : auth.orgId;
const result = await query(
`SELECT * FROM library_items WHERE id = $1 AND ($2::text IS NULL OR org_id = $2)`,
[id, orgId]
);
if (result.rowCount === 0) {
return NextResponse.json({ error: 'Library item not found' }, { status: 404 });
}
return NextResponse.json({ item: result.rows[0] });
} catch (err) {
console.error('[api/library/[id]] GET error:', (err as Error).message);
return NextResponse.json({ error: 'Failed to fetch library item' }, { status: 500 });
}
}
/**
* PATCH /api/library/[id]
* Update library item fields.
*/
export async function PATCH(request: NextRequest, context: RouteContext) {
const auth = requireRole(request, 'admin', 'staff');
if (auth instanceof NextResponse) return auth;
const { id } = await context.params;
try {
const body = await request.json();
const allowedFields = [
'title', 'description', 'content_html', 'content_text',
'tags', 'email_type', 'voice_mode', 'is_pinned', 'item_type',
];
const setClauses: string[] = [];
const values: unknown[] = [];
let paramIndex = 1;
for (const field of allowedFields) {
if (field in body) {
setClauses.push(`${field} = $${paramIndex}`);
values.push(body[field]);
paramIndex++;
}
}
if (setClauses.length === 0) {
return NextResponse.json({ error: 'No valid fields to update' }, { status: 400 });
}
const orgId = auth.role === 'admin' ? getOrgId(request) : auth.orgId;
values.push(id);
values.push(orgId);
const result = await query(
`UPDATE library_items SET ${setClauses.join(', ')} WHERE id = $${paramIndex} AND ($${paramIndex + 1}::text IS NULL OR org_id = $${paramIndex + 1}) RETURNING *`,
values
);
if (result.rowCount === 0) {
return NextResponse.json({ error: 'Library item not found' }, { status: 404 });
}
const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || undefined;
await auditLog(
'library.updated',
'library_item',
id,
{ fields: Object.keys(body).filter((k) => allowedFields.includes(k)) },
ip
);
return NextResponse.json({ item: result.rows[0] });
} catch (err) {
console.error('[api/library/[id]] PATCH error:', (err as Error).message);
return NextResponse.json({ error: 'Failed to update library item' }, { status: 500 });
}
}
/**
* DELETE /api/library/[id]
* Delete a library item.
*/
export async function DELETE(request: NextRequest, context: RouteContext) {
const auth = requireRole(request, 'admin', 'staff');
if (auth instanceof NextResponse) return auth;
const { id } = await context.params;
try {
const orgId = auth.role === 'admin' ? getOrgId(request) : auth.orgId;
const result = await query(
`DELETE FROM library_items WHERE id = $1 AND ($2::text IS NULL OR org_id = $2) RETURNING id, title, item_type`,
[id, orgId]
);
if (result.rowCount === 0) {
return NextResponse.json({ error: 'Library item not found' }, { status: 404 });
}
const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || undefined;
await auditLog(
'library.deleted',
'library_item',
id,
{ title: result.rows[0].title, item_type: result.rows[0].item_type },
ip
);
return NextResponse.json({ success: true, deleted: result.rows[0] });
} catch (err) {
console.error('[api/library/[id]] DELETE error:', (err as Error).message);
return NextResponse.json({ error: 'Failed to delete library item' }, { status: 500 });
}
}