import { api } from "@/convex/_generated/api"
import { createConvexClient, ConvexConfigurationError } from "./convex-client"

type EnsureParams = {
  tenantId: string
  slug: string
  name: string
  provisioningCode: string
}

type RemoveParams = {
  tenantId: string
  slug: string
}

export async function syncConvexCompany(params: EnsureParams): Promise<boolean> {
  try {
    const client = createConvexClient()
    const result = await client.mutation(api.companies.ensureProvisioned, params)
    return Boolean(result)
  } catch (error) {
    if (error instanceof ConvexConfigurationError) {
      console.warn("[companies-sync] Convex não configurado; sincronização ignorada.")
      return false
    }
    console.error("[companies-sync] Falha ao sincronizar empresa no Convex", error)
    throw error
  }
}

export async function removeConvexCompany(params: RemoveParams): Promise<boolean> {
  try {
    const client = createConvexClient()
    const result = await client.mutation(api.companies.removeBySlug, params)
    return Boolean(result?.removed ?? true)
  } catch (error) {
    if (error instanceof ConvexConfigurationError) {
      console.warn("[companies-sync] Convex não configurado; remoção ignorada.")
      return false
    }
    console.error("[companies-sync] Falha ao remover empresa no Convex", error)
    throw error
  }
}
