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 sessionsSchema = z.object({
  machineToken: z.string().min(1),
})

const CORS_METHODS = "POST, OPTIONS"

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

// POST /api/machines/chat/sessions
// Lista sessoes de chat ativas para a maquina
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 = sessionsSchema.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-sessions:${payload.machineToken}`,
    RATE_LIMITS.CHAT_SESSIONS.maxRequests,
    RATE_LIMITS.CHAT_SESSIONS.windowMs
  )

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

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