import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { getSessionFromRequest } from '@/lib/session'

export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const user = await getSessionFromRequest(req)
  if (!user) return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  if (user.role !== 'admin_global') return NextResponse.json({ error: 'Acesso negado' }, { status: 403 })

  const { id } = await params
  const { enabled_modules } = await req.json()

  if (!Array.isArray(enabled_modules)) {
    return NextResponse.json({ error: 'enabled_modules deve ser um array' }, { status: 400 })
  }

  await pool.execute('UPDATE tenants SET enabled_modules = ? WHERE id = ?', [
    JSON.stringify(enabled_modules),
    id,
  ])

  const [rows] = await pool.execute<any[]>('SELECT * FROM tenants WHERE id = ?', [id])
  return NextResponse.json(rows[0])
}
