import { serve } from "@hono/node-server";
import tracer from "dd-trace";
import { Hono } from "hono";
import { cors } from "hono/cors";
import { logger } from "hono/logger";
import path from "path";
import { fileURLToPath } from "url";
import { createConfig } from "./config.js";
import { MiddlewareManager } from "./middlewares/middleware.js";
import { getMainRouter } from "./routers/index.js";
import { loadSecrets, type Secrets } from "./secrets.js";

tracer.init({
  logInjection: true,
});

const __filename = fileURLToPath(import.meta.url); // get the resolved path to the file
const __dirname = path.dirname(__filename); // get the name of the directory

async function startServer(secrets: Secrets) {
  // Load configuration (will load from Google Secret Manager in production/staging)
  console.log("Initializing application configuration...");
  const config = createConfig(secrets);
  console.log(`✓ Configuration initialized for ${config.NODE_ENV} environment`);

  // Initialize middleware manager globally
  MiddlewareManager.initialize(config);

  const app = new Hono();

  app.use(logger());

  app.use("*", async (c, next) => {
    const corsMiddleware = cors({
      origin: (origin, c) => {
        if (origin.endsWith(".xtablo.com") || origin.startsWith("http://localhost")) {
          return origin;
        }
        return null;
      },
      allowHeaders: [
        "Authorization",
        "Content-Type",
        "Access-Control-Allow-Origin",
        "Access-Control-Allow-Credentials",
        "Access-Control-Expose-Headers",
      ],
      allowMethods: ["GET", "POST", "PUT", "PATCH", "OPTIONS", "DELETE"],
      exposeHeaders: ["set-cookie"],
      credentials: true,
    });

    return corsMiddleware(c, next);
  });

  app.route("/api/v1", getMainRouter(config));

  serve(
    {
      fetch: app.fetch,
      port: 8080,
    },
    (info) => {
      console.log(`✓ Server is running on http://localhost:${info.port}`);
    }
  );
  // TODO: Add health check endpoint
}

loadSecrets()
  .then((secrets) => {
    console.log("Secrets loaded successfully");
    startServer(secrets);
  })
  .catch((error) => {
    console.error("Failed to load secrets:", error);
    process.exit(1);
  });
