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

// Endpoint exclusivo para o agente local buscar tarefas pendentes
export async function GET(req: NextRequest) {
  const agentToken = req.headers.get('x-agent-token')
  if (!agentToken) return NextResponse.json({ error: 'Token obrigatório' }, { status: 401 })

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

  const tenantId = tenantRows[0].id

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

  const [tasks] = await pool.execute<any[]>(
    "SELECT * FROM agent_tasks WHERE tenant_id=? AND status='pending' ORDER BY created_at ASC LIMIT 20",
    [tenantId]
  )

  return NextResponse.json(tasks)
}
