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
  const [rows] = await pool.execute<any[]>(
    `SELECT u.*,
            t.name  AS tenantName,
            t.domain,
            t.upn_suffix AS upnSuffix
     FROM ad_users u
     LEFT JOIN tenants t ON t.id = u.tenant_id
     WHERE u.id = ?`,
    [id],
  )
  if (!rows[0]) return NextResponse.json({ error: 'Não encontrado' }, { status: 404 })

  const row = rows[0]
  // Normaliza grupos: podem vir como JSON array ou string CSV
  try { row.groups = JSON.parse(row.groups ?? '[]') } catch {
    row.groups = row.groups ? String(row.groups).split(',').filter(Boolean) : []
  }

  return NextResponse.json(row)
}

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 })

  const { id } = await params

  // Verifica que o usuário AD pertence ao tenant da sessão
  const [targetRows] = await pool.execute<any[]>('SELECT tenant_id FROM ad_users WHERE id = ?', [id])
  if (!targetRows[0]) return NextResponse.json({ error: 'Não encontrado' }, { status: 404 })
  if (user.role !== 'admin_global') {
    const sessionTenantId = (user as any).tenant_id ?? (user as any).tenantId
    if (String(targetRows[0].tenant_id) !== String(sessionTenantId)) {
      return NextResponse.json({ error: 'Acesso negado' }, { status: 403 })
    }
  }

  const body = await req.json()
  // C1: colunas corretas do schema — distinguished_name em vez de ou_path
  const { display_name, email, department, job_title, phone, distinguished_name, enabled, password_never_expires } = body

  await pool.execute(
    `UPDATE ad_users SET display_name=?, email=?, department=?, job_title=?, phone=?,
     distinguished_name=?, enabled=?, password_never_expires=?, sync_status='pending' WHERE id=?`,
    [display_name, email ?? null, department ?? null, job_title ?? null, phone ?? null,
     distinguished_name ?? null, enabled ? 1 : 0, password_never_expires ? 1 : 0, id]
  )

  // Tarefa para o agente executar no AD
  await pool.execute(
    `INSERT INTO agent_tasks (tenant_id, type, payload, status) VALUES (?, 'update_user', ?, 'pending')`,
    [targetRows[0].tenant_id, JSON.stringify({ ad_user_id: id, ...body })]
  )

  const [rows] = await pool.execute<any[]>('SELECT * FROM ad_users 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 })

  const { id } = await params
  // C2: coluna correta sam_account_name
  const [userRows] = await pool.execute<any[]>('SELECT tenant_id, sam_account_name FROM ad_users WHERE id = ?', [id])
  if (!userRows[0]) return NextResponse.json({ error: 'Não encontrado' }, { status: 404 })

  // S4: verifica tenant
  if (user.role !== 'admin_global') {
    const sessionTenantId = (user as any).tenant_id ?? (user as any).tenantId
    if (String(userRows[0].tenant_id) !== String(sessionTenantId)) {
      return NextResponse.json({ error: 'Acesso negado' }, { status: 403 })
    }
  }

  await pool.execute("UPDATE ad_users SET sync_status = 'pending_delete' WHERE id = ?", [id])

  await pool.execute(
    `INSERT INTO agent_tasks (tenant_id, type, payload, status) VALUES (?, 'delete_user', ?, 'pending')`,
    [userRows[0].tenant_id, JSON.stringify({ ad_user_id: id, sam_account_name: userRows[0].sam_account_name })]
  )

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