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

export async function POST(req: NextRequest) {
  const user = await getSessionFromRequest(req)
  if (!user) return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  if (!['admin_global', 'admin_tenant'].includes(user.role)) {
    return NextResponse.json({ error: 'Acesso negado' }, { status: 403 })
  }

  const body = await req.json()
  const { tenant_id, object_type, object_name, reason } = body
  const targetTenant = user.role === 'admin_global' ? tenant_id : user.tenant_id

  const [result] = await pool.execute<any>(
    `INSERT INTO protected_objects (tenant_id, object_type, object_name, reason) VALUES (?, ?, ?, ?)`,
    [targetTenant, object_type, object_name, reason ?? null]
  )

  const [rows] = await pool.execute<any[]>('SELECT * FROM protected_objects WHERE id = ?', [result.insertId])
  return NextResponse.json(rows[0], { status: 201 })
}

export async function DELETE(req: NextRequest) {
  const user = await getSessionFromRequest(req)
  if (!user) return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })

  const { id } = await req.json()
  await pool.execute('DELETE FROM protected_objects WHERE id = ?', [id])
  return NextResponse.json({ ok: true })
}
