export const dynamic = 'force-dynamic' import { NextRequest, NextResponse } from 'next/server' import { getSession } from '@/lib/auth/get-session' import { asAdmin, withUser } from '@/lib/db/with-user' import { writeAuditLog } from '@/lib/db/audit' import { appSettings } from '@/lib/db/schema' const ALLOWED_KEYS = [ 'DEEPSEEK_API_KEY', 'GOOGLE_AI_API_KEY', 'META_WHATSAPP_PHONE_NUMBER_ID', 'META_WHATSAPP_ACCESS_TOKEN', ] as const type SettingKey = typeof ALLOWED_KEYS[number] export async function GET() { const session = await getSession() if (!session || session.role !== 'admin') return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) const data = await asAdmin(db => db.select({ key: appSettings.key, value: appSettings.value, updatedAt: appSettings.updatedAt }) .from(appSettings) ) const masked = data.map(row => ({ key: row.key, set: Boolean(row.value), masked_value: row.value ? `${row.value.slice(0, 8)}${'•'.repeat(12)}` : '', updated_at: row.updatedAt, })) return NextResponse.json(masked) } export async function POST(request: NextRequest) { const session = await getSession() if (!session || session.role !== 'admin') return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) let body: { key?: string; value?: string } try { body = await request.json() } catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) } if (!body.key || !ALLOWED_KEYS.includes(body.key as SettingKey)) { return NextResponse.json({ error: 'Invalid key' }, { status: 422 }) } if (typeof body.value !== 'string' || body.value.trim() === '') { return NextResponse.json({ error: 'value must be a non-empty string' }, { status: 422 }) } await asAdmin(db => db.insert(appSettings).values({ key: body.key!, value: body.value!, updatedAt: new Date(), updatedBy: session.sub, }).onConflictDoUpdate({ target: appSettings.key, set: { value: body.value!, updatedAt: new Date(), updatedBy: session.sub }, }) ) await withUser(session.sub, async tx => writeAuditLog(tx, 'app_settings', session.sub, 'UPDATE', { key: body.key, set: Boolean(body.value) }) ) return NextResponse.json({ ok: true }) }