import { ensureDb } from '@/lib/db' import { NextRequest, NextResponse } from 'next/server' type ApiHandler = (req: NextRequest, ctx?: { params: Promise> }) => Promise const SECURITY_HEADERS = { 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'DENY', } function applySecurityHeaders(response: NextResponse): NextResponse { for (const [key, value] of Object.entries(SECURITY_HEADERS)) { response.headers.set(key, value) } return response } /** * Wraps an API route handler with automatic DB initialization * and security headers on all responses. * Every API route should use this to ensure tables exist before querying. */ export function withDb(handler: ApiHandler): ApiHandler { return async (req, ctx) => { try { await ensureDb() } catch (error) { console.error('[DB_INIT_ERROR]', error) const errResponse = NextResponse.json( { error: 'Database initialization failed. Please try again in a moment.' }, { status: 503 } ) return applySecurityHeaders(errResponse) } const response = await handler(req, ctx) return applySecurityHeaders(response) } }