import { z } from "zod"

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

export const runtime = "nodejs"

const schema = z.object({
  machineToken: z.string().min(1),
  provider: z.string().min(1),
  identifier: z.string().min(1),
  url: z.string().optional(),
  username: z.string().optional(),
  password: z.string().optional(),
  notes: z.string().optional(),
})

const METHODS = "POST, OPTIONS"

export async function OPTIONS(request: Request) {
  return createCorsPreflight(request.headers.get("origin"), 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, METHODS)
  }

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

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

  try {
    const response = await client.mutation(api.devices.upsertRemoteAccessViaToken, payload)
    return jsonWithCors({ ok: true, remoteAccess: response?.remoteAccess ?? null }, 200, origin, METHODS)
  } catch (error) {
    console.error("[machines.remote-access:token] Falha ao registrar acesso remoto", error)
    const details = error instanceof Error ? error.message : String(error)
    return jsonWithCors({ error: "Falha ao registrar acesso remoto", details }, 500, origin, METHODS)
  }
}
