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

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

  const { id } = await params

  // tenant_admin só pode ver o próprio tenant
  if (user.role !== 'admin_global' && user.tenant_id !== id) {
    return NextResponse.json({ error: 'Acesso negado' }, { status: 403 })
  }

  const [rows] = await pool.execute<any[]>('SELECT * FROM tenants WHERE id = ?', [id])
  if (!rows[0]) return NextResponse.json({ error: 'Não encontrado' }, { status: 404 })
  return NextResponse.json(rows[0])
}

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 body = await req.json()

  // Busca os dados atuais para usar como fallback em campos não enviados pelo payload simplificado
  const [existing] = await pool.execute<any[]>('SELECT * FROM tenants WHERE id = ?', [id])
  if (!existing[0]) return NextResponse.json({ error: 'Não encontrado' }, { status: 404 })
  const cur = existing[0]

  const name                   = body.name                   ?? cur.name
  const domain                 = body.domain                 ?? cur.domain
  const status                 = body.status                 ?? cur.status ?? 'active'
  const base_dn                = body.base_dn                !== undefined ? body.base_dn                : cur.base_dn
  const default_user_ou        = body.default_user_ou        !== undefined ? body.default_user_ou        : cur.default_user_ou
  const default_group_ou       = body.default_group_ou       !== undefined ? body.default_group_ou       : cur.default_group_ou
  const preferred_dc           = body.preferred_dc           !== undefined ? body.preferred_dc           : cur.preferred_dc
  const ldap_port              = body.ldap_port              !== undefined ? body.ldap_port              : cur.ldap_port
  const use_ssl                = body.use_ssl                !== undefined ? body.use_ssl                : cur.use_ssl
  const upn_suffix             = body.upn_suffix             !== undefined ? body.upn_suffix             : cur.upn_suffix
  const ad_service_user        = body.ad_service_user        !== undefined ? body.ad_service_user        : cur.ad_service_user
  // Senha: só atualiza se vier preenchida no body (não sobrescreve com undefined)
  const ad_service_password    = body.ad_service_password    ? body.ad_service_password                 : cur.ad_service_password
  const allow_global_admin_access = body.allow_global_admin_access !== undefined
    ? (body.allow_global_admin_access ? 1 : 0)
    : cur.allow_global_admin_access

  await pool.execute(
    `UPDATE tenants SET
      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=?
     WHERE id=?`,
    [
      name, domain, status,
      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,
      id,
    ],
  )

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

export async function DELETE(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 [rows] = await pool.execute<any[]>('SELECT status FROM tenants WHERE id = ?', [id])
  if (!rows[0]) return NextResponse.json({ error: 'Não encontrado' }, { status: 404 })
  if (rows[0].status !== 'inactive') {
    return NextResponse.json(
      { error: 'A empresa precisa estar inativa antes de ser excluída.' },
      { status: 400 },
    )
  }

  // Remove usuários do portal vinculados e depois o tenant
  await pool.execute('DELETE FROM portal_users WHERE tenant_id = ?', [id])
  await pool.execute('DELETE FROM tenants WHERE id = ?', [id])

  return NextResponse.json({ ok: true })
}
