import { NextResponse } from "next/server"
import { z } from "zod"
import { ConvexHttpClient } from "convex/browser"

import { assertAuthenticatedSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { api } from "@/convex/_generated/api"

export const runtime = "nodejs"

const schema = z.object({
  machineId: z.string().min(1),
})

export async function POST(request: Request) {
  const session = await assertAuthenticatedSession()
  if (!session) {
    return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
  }

  const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL
  if (!convexUrl) {
    return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
  }

  const payload = await request.json().catch(() => null)
  const parsed = schema.safeParse(payload)
  if (!parsed.success) {
    return NextResponse.json({ error: "Payload inválido", details: parsed.error.flatten() }, { status: 400 })
  }

  const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID

  try {
    const convex = new ConvexHttpClient(convexUrl)
    const ensured = await convex.mutation(api.users.ensureUser, {
      tenantId,
      email: session.user.email,
      name: session.user.name ?? session.user.email,
      avatarUrl: session.user.avatarUrl ?? undefined,
      role: session.user.role.toUpperCase(),
    })
    const actorId = ensured?._id
    if (!actorId) {
      return NextResponse.json({ error: "Falha ao obter ID do usuário no Convex" }, { status: 500 })
    }

    const client = convex as unknown as { mutation: (name: string, args: unknown) => Promise<unknown> }
    const result = (await client.mutation("machines:resetAgent", {
      machineId: parsed.data.machineId,
      actorId,
    })) as { revoked?: number } | null

    return NextResponse.json({ ok: true, revoked: result?.revoked ?? 0 })
  } catch (error) {
    console.error("[machines.resetAgent] Falha ao resetar agente", error)
    return NextResponse.json({ error: "Falha ao resetar agente da dispositivo" }, { status: 500 })
  }
}

