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 tenantId =
    user.role === 'admin_global'
      ? (req.nextUrl.searchParams.get('tenant_id') ?? '')
      : ((user as any).tenantId ?? (user as any).tenant_id ?? '')

  if (!tenantId) return NextResponse.json({ error: 'Tenant não informado' }, { status: 400 })

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

  const [policyRows] = await pool.execute<any[]>(
    'SELECT * FROM tenant_policies WHERE tenant_id = ?',
    [tenantId],
  )

  // Nunca retorna a senha para o cliente — expõe apenas se existe
  const { ad_service_password: _pwd, ...safeTenant } = tenantRows[0]

  return NextResponse.json({
    tenant: { ...safeTenant, has_password: !!tenantRows[0].ad_service_password },
    policies: policyRows[0] ?? null,
  })
}

export async function PUT(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()

  const tenantId =
    user.role === 'admin_global'
      ? (body.tenant_id ?? '')
      : ((user as any).tenantId ?? (user as any).tenant_id ?? '')

  if (!tenantId) return NextResponse.json({ error: 'Tenant não informado' }, { status: 400 })

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

  const preferred_dc        = body.preferred_dc        !== undefined ? body.preferred_dc        : cur.preferred_dc
  const ldap_port           = body.ldap_port           !== undefined ? Number(body.ldap_port)   : cur.ldap_port
  const use_ssl             = body.use_ssl             !== undefined ? body.use_ssl             : cur.use_ssl
  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 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
  // Só sobrescreve a senha se vier preenchida
  const ad_service_password = body.ad_service_password ? body.ad_service_password               : cur.ad_service_password

  await pool.execute(
    `UPDATE tenants SET
       preferred_dc=?, ldap_port=?, use_ssl=?,
       base_dn=?, default_user_ou=?, default_group_ou=?,
       upn_suffix=?, ad_service_user=?, ad_service_password=?
     WHERE id=?`,
    [
      preferred_dc ?? null, ldap_port ?? 389, use_ssl ? 1 : 0,
      base_dn ?? null, default_user_ou ?? null, default_group_ou ?? null,
      upn_suffix ?? null, ad_service_user ?? null, ad_service_password ?? null,
      tenantId,
    ],
  )

  // Salva políticas se enviadas
  if (body.policy) {
    const p = body.policy
    await pool.execute(
      `INSERT INTO tenant_policies
         (tenant_id, must_change_password_on_first, cannot_change_password,
          password_never_expires, account_starts_enabled, operator_can_choose_must_change,
          operator_can_choose_cannot_change, operator_can_choose_never_expires, operator_can_choose_enabled)
       VALUES (?,?,?,?,?,?,?,?,?)
       ON DUPLICATE KEY UPDATE
         must_change_password_on_first=VALUES(must_change_password_on_first),
         cannot_change_password=VALUES(cannot_change_password),
         password_never_expires=VALUES(password_never_expires),
         account_starts_enabled=VALUES(account_starts_enabled),
         operator_can_choose_must_change=VALUES(operator_can_choose_must_change),
         operator_can_choose_cannot_change=VALUES(operator_can_choose_cannot_change),
         operator_can_choose_never_expires=VALUES(operator_can_choose_never_expires),
         operator_can_choose_enabled=VALUES(operator_can_choose_enabled)`,
      [
        tenantId,
        p.mustChangePasswordOnFirstLogin ? 1 : 0,
        p.cannotChangePassword ? 1 : 0,
        p.passwordNeverExpires ? 1 : 0,
        p.accountStartsEnabled ? 1 : 0,
        p.operatorCanChooseMustChange ? 1 : 0,
        p.operatorCanChooseCannotChange ? 1 : 0,
        p.operatorCanChooseNeverExpires ? 1 : 0,
        p.operatorCanChooseEnabled ? 1 : 0,
      ],
    )
  }

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