import { NextRequest, NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
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 isGlobal = user.role === 'admin_global'
  let rows: any[]

  if (isGlobal) {
    const [r] = await pool.execute<any[]>(
      `SELECT u.id, u.name, u.email, u.role, u.tenant_id, u.status,
              u.mfa_enabled, u.last_login, u.created_at, t.name as tenant_name
       FROM portal_users u
       LEFT JOIN tenants t ON t.id = u.tenant_id
       ORDER BY u.created_at DESC`,
    )
    rows = r
  } else {
    const [r] = await pool.execute<any[]>(
      `SELECT u.id, u.name, u.email, u.role, u.tenant_id, u.status,
              u.mfa_enabled, u.last_login, u.created_at, t.name as tenant_name
       FROM portal_users u
       LEFT JOIN tenants t ON t.id = u.tenant_id
       WHERE u.tenant_id = ? ORDER BY u.created_at DESC`,
      [user.tenant_id],
    )
    rows = r
  }

  return NextResponse.json(rows)
}

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

  const body = await req.json()
  const { name, email, role, tenant_id, password, mfa_enabled } = body

  if (!name || !email || !role || !password) {
    return NextResponse.json({ error: 'Campos obrigatórios faltando' }, { status: 400 })
  }

  const targetTenantId = sessionUser.role === 'admin_global' ? (tenant_id ?? null) : sessionUser.tenant_id

  const hash = await bcrypt.hash(password, 12)

  const [result] = await pool.execute<any>(
    `INSERT INTO portal_users (name, email, role, tenant_id, password_hash, mfa_enabled, status)
     VALUES (?, ?, ?, ?, ?, ?, 'active')`,
    [name, email, role, targetTenantId, hash, mfa_enabled ? 1 : 0],
  )

  const [rows] = await pool.execute<any[]>(
    'SELECT id, name, email, role, tenant_id, status, mfa_enabled, created_at FROM portal_users WHERE id = ?',
    [result.insertId],
  )
  return NextResponse.json(rows[0], { status: 201 })
}
