import { env } from "@haushaltsApp/env/server";
import { Hono } from "hono";
import { cors } from "hono/cors";
import { logger } from "hono/logger";
import { injectWebSocket } from "./ws/bun-ws";
import { registerRoutes } from "./routes";

const app = new Hono();

app.use(logger());
app.use(
  "/*",
  cors({
    origin: env.CORS_ORIGIN,
    allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allowHeaders: ["Content-Type", "Authorization", "x-household-id"],
    credentials: true,
  }),
);

registerRoutes(app);

if (typeof Bun !== "undefined" && !process.env.BUN_TEST) {
  const server = Bun.serve({
    port: Number(process.env.PORT ?? 3000),
    hostname: "0.0.0.0",
    fetch: app.fetch,
  });
  injectWebSocket(server);
}

export default app;
