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

export async function POST(req: NextRequest) {
  const agentToken = req.headers.get('x-agent-token') ?? ''
  if (!agentToken) return NextResponse.json({ error: 'Token ausente' }, { status: 401 })

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

  const body = await req.json().catch(() => ({}))

  await pool.execute(
    `UPDATE tenants SET agent_last_seen = NOW(), agent_status = 'online',
     agent_version = COALESCE(?, agent_version)
     WHERE id = ?`,
    [body.version ?? null, rows[0].id],
  )

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