import { z } from "zod"

import { api } from "@/convex/_generated/api"
import { createCorsPreflight, jsonWithCors } from "@/server/cors"
import { createConvexClient, ConvexConfigurationError } from "@/server/convex-client"

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) {
  const origin = request.headers.get("origin")
  if (request.method !== "POST") {
    return jsonWithCors({ error: "Método não permitido" }, 405, origin, CORS_METHODS)
  }

  let client
  try {
    client = createConvexClient()
  } catch (error) {
    if (error instanceof ConvexConfigurationError) {
      return jsonWithCors({ error: error.message }, 500, origin, CORS_METHODS)
    }
    throw error
  }

  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,
      origin,
      CORS_METHODS
    )
  }

  try {
    const response = await client.mutation(api.machines.heartbeat, payload)
    return jsonWithCors(response, 200, 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, origin, CORS_METHODS)
  }
}
