import dotenv from "dotenv";
dotenv.config();

import express, { Request, Response, NextFunction } from "express";
import http from "http"; // For controlling keepAliveTimeout
import path from "path";
import apiRoutes from "./routes/apiRoutes";
import { initializeClients, redisClient, clickhouseService } from "./services/clients"; // 导入新的初始化函数和客户端

const app = express();
const port = process.env.PORT || 3000;

// Middleware
app.set("trust proxy", true);
app.use(express.json());

// API routes
app.use("/api", apiRoutes);

// Static and SPA routing... (Keep your existing code here)
let publicPath: string;
let angularAppPath: string;
if (process.env.NODE_ENV === "production") {
  publicPath = path.resolve(__dirname, "..", "..", "public");
  angularAppPath = path.join(publicPath, "app");
} else {
  publicPath = path.resolve(__dirname, "..", "public");
  angularAppPath = path.join(publicPath, "app");
}
console.log(process.env.NODE_ENV);
console.log(`publicPath: ${publicPath}`);
console.log(`angularAppPath: ${angularAppPath}`);
app.use(express.static(publicPath));
app.use((req: Request, res: Response) => {
  res.sendFile(path.join(angularAppPath, "index.html"));
});

// Start the server
async function startServer() {
  await initializeClients(); // 先初始化所有客户端
  const server = http.createServer(app);
  // server.keepAliveTimeout = 61 * 1000;
  // server.headersTimeout = 65 * 1000;
  server.listen(port, () => {
    console.log(`OMS Backend server listening on port ${port}`);
  });
}

startServer();

// Export services/clients if needed by other modules
export { redisClient, clickhouseService };
