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

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

  const userId = req.nextUrl.searchParams.get('user_id')
  const queryParams: any[] = []
  let where = 'WHERE 1=1'

  if (userId) {
    where += ' AND p.user_id = ?'
    queryParams.push(userId)
  } else if (user.role !== 'admin_global') {
    where += ' AND u.tenant_id = ?'
    queryParams.push((user as any).tenant_id ?? (user as any).tenantId)
  }

  const [rows] = await pool.execute<any[]>(
    `SELECT p.*, u.name as user_name, u.email as user_email
     FROM portal_user_permissions p
     INNER JOIN portal_users u ON u.id = p.user_id
     ${where} ORDER BY p.id DESC`,
    queryParams
  )
  return NextResponse.json(rows)
}

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', 'tenant_admin'].includes(user.role)) {
    return NextResponse.json({ error: 'Acesso negado' }, { status: 403 })
  }

  const body = await req.json()
  // Schema real: user_id, module, actions (JSON array de strings)
  const { user_id, module, actions } = body

  if (!user_id || !module) {
    return NextResponse.json({ error: 'user_id e module são obrigatórios' }, { status: 400 })
  }

  // tenant_admin só pode gerir permissões do próprio tenant
  if (user.role !== 'admin_global') {
    const [targetUser] = await pool.execute<any[]>('SELECT tenant_id FROM portal_users WHERE id = ?', [user_id])
    const sessionTenantId = (user as any).tenant_id ?? (user as any).tenantId
    if (String(targetUser[0]?.tenant_id) !== String(sessionTenantId)) {
      return NextResponse.json({ error: 'Acesso negado' }, { status: 403 })
    }
  }

  const actionsJson = JSON.stringify(Array.isArray(actions) ? actions : [])

  await pool.execute(
    `INSERT INTO portal_user_permissions (user_id, module, actions)
     VALUES (?, ?, ?)
     ON DUPLICATE KEY UPDATE actions = VALUES(actions)`,
    [user_id, module, actionsJson]
  )

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