import { z } from "zod"

import { api } from "@/convex/_generated/api"
import { createCorsPreflight, jsonWithCors } from "@/server/cors"
import { createConvexClient, ConvexConfigurationError } from "@/server/convex-client"
import { checkRateLimit, RATE_LIMITS, rateLimitHeaders } from "@/server/rate-limit"

const pollSchema = z.object({
  machineToken: z.string().min(1),
  lastCheckedAt: z.number().optional(),
})

const CORS_METHODS = "POST, OPTIONS"

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

// POST /api/machines/chat/poll
// Endpoint leve para polling de atualizacoes de chat
export async function POST(request: Request) {
  const origin = request.headers.get("origin")

  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 = pollSchema.parse(raw)
  } catch (error) {
    return jsonWithCors(
      { error: "Payload invalido", details: error instanceof Error ? error.message : String(error) },
      400,
      origin,
      CORS_METHODS
    )
  }

  // Rate limiting por token de maquina
  const rateLimit = checkRateLimit(
    `chat-poll:${payload.machineToken}`,
    RATE_LIMITS.CHAT_POLL.maxRequests,
    RATE_LIMITS.CHAT_POLL.windowMs
  )

  if (!rateLimit.allowed) {
    return jsonWithCors(
      { error: "Rate limit exceeded", retryAfterMs: rateLimit.retryAfterMs },
      429,
      origin,
      CORS_METHODS,
      rateLimitHeaders(rateLimit)
    )
  }

  try {
    const result = await client.query(api.liveChat.checkMachineUpdates, {
      machineToken: payload.machineToken,
      lastCheckedAt: payload.lastCheckedAt,
    })
    return jsonWithCors(result, 200, origin, CORS_METHODS, rateLimitHeaders(rateLimit))
  } catch (error) {
    console.error("[machines.chat.poll] Falha ao verificar atualizacoes", error)
    const details = error instanceof Error ? error.message : String(error)
    return jsonWithCors({ error: "Falha ao verificar atualizacoes", details }, 500, origin, CORS_METHODS)
  }
}
