import { createClient } from "redis";
import { ClickhouseService } from "./clickhouseService";
import { connectToDatabase } from "../database";

// ClickHouse settings
const clickhouseHost = process.env.CLICKHOUSE_HOST || "http://localhost:8123";
const clickhouseDatabase = process.env.CLICKHOUSE_DATABASE || "omsdb";
const clickhouseUser = process.env.CLICKHOUSE_USER || "ckuser";
const clickhousePassword = process.env.CLICKHOUSE_PASSWORD || "ckpassword";

// MongoDB connection
connectToDatabase();

// Redis client
const redisUri = process.env.REDIS_URI || "redis://localhost:6379";
const redisClient = createClient({ url: redisUri });
redisClient.on("connect", () => console.log("Connected to Redis"));
redisClient.on("error", (err: any) => console.error("Redis connection error:", err));

// Clickhouse client
const clickhouseService = new ClickhouseService(clickhouseHost, clickhouseDatabase, clickhouseUser, clickhousePassword);
const clickhouseTableName = "events";

// Initialize essential services
export async function initializeClients() {
  try {
    await redisClient.connect();
    await clickhouseService.ensureTable(clickhouseTableName);
    console.log("[Clients] All essential services connected successfully.");
  } catch (err) {
    console.error("[Clients] Failed to connect to essential services:", err);
    process.exit(1);
  }
}

// Export the initialized clients
export { redisClient, clickhouseService };
