import Swagger from "@elysiajs/swagger";
import Elysia from "elysia";
import html from "./index.html";
import apiAuth from "./server/middlewares/apiAuth";
import ApiKeyRoute from "./server/routes/apikey_route";
import Auth from "./server/routes/auth_route";
import CredentialRoute from "./server/routes/credential_route";
import DarmasabaRoute from "./server/routes/darmasaba_route";
import { convertOpenApiToMcp } from "./server/lib/mcp-converter";
import UserRoute from "./server/routes/user_route";
import LayananRoute from "./server/routes/layanan_route";
import AduanRoute from "./server/routes/aduan_route";

import { cors } from "@elysiajs/cors";
import { MCPRoute } from "./server/routes/mcp_route";

const Docs = new Elysia({
  tags: ["docs"],
}).use(
  Swagger({
    path: "/docs",
  }),
);

const Api = new Elysia({
  prefix: "/api",
  tags: ["api"],
})
  .use(apiAuth)
  .use(ApiKeyRoute)
  .use(DarmasabaRoute)
  .use(CredentialRoute)
  .use(UserRoute)
  .use(LayananRoute)
  .use(AduanRoute);

const app = new Elysia()
  .use(Api)
  .use(Docs)
  .use(Auth)
  .get(
    "/.well-known/mcp.json",
    async () => {
      const baseUrl = process.env.BUN_PUBLIC_BASE_URL!;
      return await convertOpenApiToMcp(baseUrl);
    },
    {
      detail: {
        description: "MCP manifest",
        tags: ["MCP"],
      },
    },
  )
  .use(MCPRoute)
  // .get("/*", html)
  .onRequest(({ set }) => {
    set.headers["Access-Control-Allow-Origin"] = "*";
    set.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
    set.headers["Access-Control-Allow-Headers"] = "Content-Type";
  })
  .listen(3000, () => {
    console.log("Server running at http://localhost:3000");
  });

export type ServerApp = typeof app;
