import { z } from "zod"
import { ConvexHttpClient } from "convex/browser"

import { api } from "@/convex/_generated/api"
import { env } from "@/lib/env"
import { createCorsPreflight, jsonWithCors } from "@/server/cors"

const heartbeatSchema = z.object({
  machineToken: z.string().min(1),
  status: z.string().optional(),
  hostname: z.string().optional(),
  os: z
    .object({
      name: z.string(),
      version: z.string().optional(),
      architecture: z.string().optional(),
    })
    .optional(),
  metrics: z.record(z.string(), z.unknown()).optional(),
  inventory: z.record(z.string(), z.unknown()).optional(),
  metadata: z.record(z.string(), z.unknown()).optional(),
})

const CORS_METHODS = "POST, OPTIONS"

export async function OPTIONS(request: Request) {
  return createCorsPreflight(request.headers.get("origin"), CORS_METHODS)
}

export async function POST(request: Request) {
  if (request.method !== "POST") {
    return jsonWithCors({ error: "Método não permitido" }, 405, request.headers.get("origin"), CORS_METHODS)
  }

  const convexUrl = env.NEXT_PUBLIC_CONVEX_URL
  if (!convexUrl) {
    return jsonWithCors({ error: "Convex não configurado" }, 500, request.headers.get("origin"), CORS_METHODS)
  }

  let payload
  try {
    const raw = await request.json()
    payload = heartbeatSchema.parse(raw)
  } catch (error) {
    return jsonWithCors(
      { error: "Payload inválido", details: error instanceof Error ? error.message : String(error) },
      400,
      request.headers.get("origin"),
      CORS_METHODS
    )
  }

  const client = new ConvexHttpClient(convexUrl)

  try {
    const response = await client.mutation(api.machines.heartbeat, payload)
    return jsonWithCors(response, 200, request.headers.get("origin"), CORS_METHODS)
  } catch (error) {
    console.error("[machines.heartbeat] Falha ao registrar heartbeat", error)
    const details = error instanceof Error ? error.message : String(error)
    return jsonWithCors({ error: "Falha ao registrar heartbeat", details }, 500, request.headers.get("origin"), CORS_METHODS)
  }
}
