import cors from "cors";
import express from "express";
import { checkDatabase } from "../db/client.js";
import { previewRouter } from "../preview/routes.js";
import { projectsRouter } from "../projects/routes.js";
import { settingsRouter } from "../settings/routes.js";
import { storageProvider } from "../storage/index.js";

export function createServer() {
  const app = express();

  app.use(cors({ exposedHeaders: ["Content-Disposition"] }));
  app.use(express.json({ limit: "150mb" }));

  app.use("/projects", projectsRouter);
  app.use("/preview", previewRouter);
  app.use("/settings", settingsRouter);

  app.get("/health", (_request, response) => {
    response.json({
      status: "ok",
      service: "seo_mode-server"
    });
  });

  app.get("/health/deep", async (_request, response) => {
    const checks: Record<string, unknown> = {};

    try {
      checks.database = await checkDatabase();
    } catch (error) {
      checks.database = { error: error instanceof Error ? error.message : "unknown error" };
    }

    try {
      await storageProvider.ensureReady();
      checks.objectStorage = { status: "ok" };
    } catch (error) {
      checks.objectStorage = { error: error instanceof Error ? error.message : "unknown error" };
    }

    const hasError = Object.values(checks).some((value) => {
      return typeof value === "object" && value !== null && "error" in value;
    });

    response.status(hasError ? 503 : 200).json({
      status: hasError ? "degraded" : "ok",
      checks
    });
  });

  return app;
}
