import { createClient } from "@clickhouse/client";
import { config } from "../config";
import { logger } from "./logger";

const client = config.CLICKHOUSE_ANALYTICS_URL
  ? createClient({
      url: config.CLICKHOUSE_ANALYTICS_URL,
      database: config.CLICKHOUSE_ANALYTICS_DATABASE ?? "default",
      clickhouse_settings: {
        async_insert: 1,
        wait_for_async_insert: 0,
      },
    })
  : null;

export async function chInsert(
  table: string,
  rows: Record<string, unknown>[],
): Promise<void> {
  if (!client || rows.length === 0) return;

  try {
    await client.insert({
      table,
      values: rows,
      format: "JSONEachRow",
    });
  } catch (error: any) {
    logger.error("ClickHouse insert failed", {
      table,
      rowCount: rows.length,
      error: error?.message,
    });
  }
}
