import { NextRequest, NextResponse } from 'next/server'
import { query } from '@/lib/db'

// GET() sem parâmetros seria tratado como rota estática pelo Next e cacheado
// permanentemente a partir do build — precisa ser explicitamente dinâmico.
export const dynamic = 'force-dynamic'

export async function GET() {
  const rows = await query<{ key: string; value: string }>(
    `SELECT key, value FROM portal_config ORDER BY key`,
    [],
  )
  const cfg: Record<string, string> = {}
  for (const r of rows) cfg[r.key] = r.value
  return NextResponse.json(cfg)
}

export async function PATCH(req: NextRequest) {
  const body = await req.json() as Record<string, string>
  for (const [key, value] of Object.entries(body)) {
    await query(
      `INSERT INTO portal_config (key, value) VALUES ($1, $2)
       ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
      [key, value],
    )
  }
  return NextResponse.json({ ok: true })
}
