// Force this API route to use Node.js runtime for database access export const runtime = "nodejs"; import db from "@/lib/db"; import { NextResponse } from "next/server"; import { withUserAuth } from "@/lib/middleware/auth"; import { logApiActionSafe, AUDIT_ACTIONS, RESOURCE_TYPES, } from "@/lib/auditLogSafe.js"; import initializeDatabase from "@/lib/init-db"; // Make sure the DB is initialized before queries run initializeDatabase(); async function deleteNoteHandler(req, { params }) { const { id } = await params; if (!id) { return NextResponse.json({ error: "Note ID is required" }, { status: 400 }); } try { // Get note data before deletion for audit log const note = db.prepare("SELECT * FROM notes WHERE note_id = ?").get(id); if (!note) { return NextResponse.json({ error: "Note not found" }, { status: 404 }); } // Check if user has permission to delete this note // Users can delete their own notes, or admins can delete any note const userRole = req.user?.role; const userId = req.user?.id; if (userRole !== 'admin' && note.created_by !== userId) { return NextResponse.json({ error: "Unauthorized to delete this note" }, { status: 403 }); } // Delete the note db.prepare("DELETE FROM notes WHERE note_id = ?").run(id); // Log note deletion await logApiActionSafe( req, AUDIT_ACTIONS.NOTE_DELETE, RESOURCE_TYPES.NOTE, id, req.auth, { deletedNote: { project_id: note?.project_id, task_id: note?.task_id, note_length: note?.note?.length || 0, created_by: note?.created_by, }, } ); return NextResponse.json({ success: true }); } catch (error) { console.error("Error deleting note:", error); return NextResponse.json( { error: "Failed to delete note", details: error.message }, { status: 500 } ); } } // Protected route - require user authentication export const DELETE = withUserAuth(deleteNoteHandler);