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

export async function GET(req: NextRequest) {
  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 [rows] = await pool.execute<any[]>('SELECT * FROM tenants ORDER BY created_at DESC')
  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 (user.role !== 'admin_global') return NextResponse.json({ error: 'Acesso negado' }, { status: 403 })

  const body = await req.json()
  const {
    name, domain,
    base_dn, default_user_ou, default_group_ou,
    preferred_dc, ldap_port, use_ssl, upn_suffix,
    ad_service_user, ad_service_password,
    allow_global_admin_access,
    // admin inicial obrigatório na criação
    admin_name, admin_email, admin_password,
  } = body

  if (!name?.trim()) return NextResponse.json({ error: 'Nome é obrigatório' }, { status: 400 })
  if (!domain?.trim()) return NextResponse.json({ error: 'Domínio é obrigatório' }, { status: 400 })
  if (!admin_name?.trim()) return NextResponse.json({ error: 'Nome do administrador é obrigatório' }, { status: 400 })
  if (!admin_email?.trim()) return NextResponse.json({ error: 'E-mail do administrador é obrigatório' }, { status: 400 })
  if (!admin_password || admin_password.length < 8) return NextResponse.json({ error: 'Senha do administrador deve ter ao menos 8 caracteres' }, { status: 400 })

  // Verificar e-mail duplicado
  const [existingEmail] = await pool.execute<any[]>('SELECT id FROM portal_users WHERE email = ? LIMIT 1', [admin_email])
  if ((existingEmail as any[]).length > 0) {
    return NextResponse.json({ error: 'Já existe um usuário com este e-mail no portal' }, { status: 409 })
  }

  try {
    // Gerar UUID para o tenant antecipadamente
    const tenantId = crypto.randomUUID()
    const agentToken = `agt_${crypto.randomUUID().replace(/-/g, '')}`

    // 1. Criar o tenant com o UUID gerado
    await pool.query(
      `INSERT INTO tenants (
        id, name, domain, status,
        base_dn, default_user_ou, default_group_ou,
        preferred_dc, ldap_port, use_ssl, upn_suffix,
        ad_service_user, ad_service_password,
        allow_global_admin_access, agent_token
      ) VALUES (?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        tenantId,
        name, domain,
        base_dn ?? null, default_user_ou ?? null, default_group_ou ?? null,
        preferred_dc ?? null, ldap_port ?? 389, use_ssl ? 1 : 0, upn_suffix ?? null,
        ad_service_user ?? null, ad_service_password ?? null,
        allow_global_admin_access !== false ? 1 : 0,
        agentToken,
      ],
    )

    // 2. Criar o admin inicial da empresa usando o mesmo UUID
    const hash = await bcrypt.hash(admin_password, 12)
    const adminId = crypto.randomUUID()
    await pool.query(
      `INSERT INTO portal_users (id, tenant_id, name, email, password_hash, role, status)
       VALUES (?, ?, ?, ?, ?, 'tenant_admin', 'active')`,
      [adminId, tenantId, admin_name, admin_email, hash],
    )

    const [[tenant]] = await pool.query<any[]>('SELECT * FROM tenants WHERE id = ?', [tenantId])
    return NextResponse.json(tenant, { status: 201 })
  } catch (err: any) {
    return NextResponse.json({ error: 'Erro ao criar empresa: ' + err.message }, { status: 500 })
  }
}
