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

export const runtime = "nodejs"

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")
  let payload: unknown
  try {
    payload = await request.json()
  } catch (error) {
    return jsonWithCors(
      { error: "Payload inválido", details: error instanceof Error ? error.message : String(error) },
      400,
      origin,
      CORS_METHODS
    )
  }

  const provisioningCodeRaw =
    payload && typeof payload === "object" && "provisioningCode" in payload
      ? (payload as { provisioningCode?: unknown }).provisioningCode
      : null

  const provisioningCode =
    typeof provisioningCodeRaw === "string" ? provisioningCodeRaw.trim().toLowerCase() : ""
  if (!provisioningCode) {
    return jsonWithCors({ error: "Informe o código de provisionamento" }, 400, origin, CORS_METHODS)
  }

  try {
    const company = await prisma.company.findFirst({
      where: { provisioningCode },
      select: {
        id: true,
        tenantId: true,
        name: true,
        slug: true,
        provisioningCode: true,
      },
    })

    if (!company) {
      return jsonWithCors({ error: "Código de provisionamento inválido" }, 404, origin, CORS_METHODS)
    }

    try {
      const client = createConvexClient()
      await client.mutation(api.companies.ensureProvisioned, {
        tenantId: company.tenantId,
        slug: company.slug,
        name: company.name,
        provisioningCode: company.provisioningCode,
      })
    } catch (error) {
      if (error instanceof ConvexConfigurationError) {
        console.warn("[machines.provisioning] Convex não configurado; ignorando sincronização de empresa.")
      } else {
        console.error("[machines.provisioning] Falha ao sincronizar empresa no Convex", error)
      }
    }

    return jsonWithCors(
      {
        company: {
          id: company.id,
          tenantId: company.tenantId,
          name: company.name,
          slug: company.slug,
        },
      },
      200,
      origin,
      CORS_METHODS
    )
  } catch (error) {
    console.error("[machines.provisioning] Falha ao validar código", error)
    return jsonWithCors(
      { error: "Falha ao validar código de provisionamento" },
      500,
      origin,
      CORS_METHODS
    )
  }
}
