// Force this API route to use Node.js runtime for database access export const runtime = "nodejs"; import { getFieldHistory, hasFieldHistory } from "@/lib/queries/fieldHistory"; import { NextResponse } from "next/server"; import { withReadAuth } from "@/lib/middleware/auth"; import initializeDatabase from "@/lib/init-db"; // Make sure the DB is initialized before queries run initializeDatabase(); async function getFieldHistoryHandler(req) { const { searchParams } = new URL(req.url); const tableName = searchParams.get("table_name"); const recordId = searchParams.get("record_id"); const fieldName = searchParams.get("field_name"); const checkOnly = searchParams.get("check_only") === "true"; if (!tableName || !recordId || !fieldName) { return NextResponse.json( { error: "Missing required parameters: table_name, record_id, field_name" }, { status: 400 } ); } try { if (checkOnly) { // Just check if history exists const exists = hasFieldHistory(tableName, parseInt(recordId), fieldName); return NextResponse.json({ hasHistory: exists }); } else { // Get full history const history = getFieldHistory(tableName, parseInt(recordId), fieldName); return NextResponse.json(history); } } catch (error) { console.error("Error fetching field history:", error); return NextResponse.json( { error: "Failed to fetch field history" }, { status: 500 } ); } } // Protected route - require read authentication export const GET = withReadAuth(getFieldHistoryHandler);