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

// Portal: busca status e tarefas do agente do tenant atual
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.tenant_id
    : user.tenant_id

  const [tenantRows] = await pool.execute<any[]>(
    'SELECT id, name, agent_token, agent_last_seen, agent_version, agent_status FROM tenants WHERE id = ?',
    [tenantId]
  )

  const [tasks] = await pool.execute<any[]>(
    `SELECT * FROM agent_tasks WHERE tenant_id = ? ORDER BY created_at DESC LIMIT 50`,
    [tenantId]
  )

  return NextResponse.json({ tenant: tenantRows[0] ?? null, tasks })
}

// Portal: gera ou revoga token do agente
export async function POST(req: NextRequest) {
  const user = await getSessionFromRequest(req)
  if (!user) return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })

  const body = await req.json()
  const { tenant_id, action } = body

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

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

  if (user.role !== 'admin_global' && ((user as any).tenantId ?? (user as any).tenant_id) !== tenantId) {
    return NextResponse.json({ error: 'Acesso negado' }, { status: 403 })
  }

  if (action === 'generate_token') {
    const newToken = `agt_${crypto.randomUUID().replace(/-/g, '')}`
    await pool.execute('UPDATE tenants SET agent_token = ? WHERE id = ?', [newToken, tenantId])
    return NextResponse.json({ token: newToken })
  }

  if (action === 'revoke_token') {
    await pool.execute('UPDATE tenants SET agent_token = NULL WHERE id = ?', [tenantId])
    return NextResponse.json({ ok: true })
  }

  return NextResponse.json({ error: 'Ação inválida' }, { status: 400 })
}

// Agente local: busca tarefas pendentes (autenticado via agent_token no header)
export async function PATCH(req: NextRequest) {
  const agentToken = req.headers.get('x-agent-token')
  if (!agentToken) return NextResponse.json({ error: 'Token do agente obrigatório' }, { status: 401 })

  const [tenantRows] = await pool.execute<any[]>(
    'SELECT id FROM tenants WHERE agent_token = ? AND status = ?',
    [agentToken, 'active']
  )
  if (!tenantRows[0]) return NextResponse.json({ error: 'Token inválido' }, { status: 401 })

  const tenantId = tenantRows[0].id
  const body = await req.json()
  const { task_id, status, result } = body

  await pool.execute(
    `UPDATE agent_tasks SET status=?, result=?, executed_at=NOW() WHERE id=? AND tenant_id=?`,
    [status, result ? JSON.stringify(result) : null, task_id, tenantId]
  )

  // Atualiza last_seen do agente
  await pool.execute(
    `UPDATE tenants SET agent_last_seen=NOW(), agent_status='online' WHERE id=?`,
    [tenantId]
  )

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