import { Hono } from "hono";
import type { AppConfig } from "../config.js";
import { type AdminTokenResult, exchangePrivilegedToken } from "../helpers/adminTokens.js";
import { MiddlewareManager } from "../middlewares/middleware.js";
import type { BaseEnv } from "../types/app.types.js";

export const getAdminAuthRouter = (config: AppConfig) => {
  const adminAuthRouter = new Hono<BaseEnv>();
  const middlewareManager = MiddlewareManager.getInstance();
  const isAdminTokenFailure = <T>(
    result: AdminTokenResult<T>
  ): result is Extract<AdminTokenResult<T>, { success: false }> => !result.success;

  adminAuthRouter.post("/exchange", async (c) => {
    const body = await c.req.json().catch(() => null);
    const accessToken =
      body && typeof body === "object" && "accessToken" in body ? body.accessToken : undefined;

    if (typeof accessToken !== "string" || accessToken.length === 0) {
      return c.json(
        {
          code: "INVALID_ADMIN_ACCESS_TOKEN",
          error: "Invalid privileged access token",
        },
        401
      );
    }

    const exchangeResult = exchangePrivilegedToken(accessToken, config);

    if (isAdminTokenFailure(exchangeResult)) {
      return c.json(
        {
          code: exchangeResult.code,
          error: exchangeResult.error,
        },
        exchangeResult.statusCode
      );
    }

    return c.json(exchangeResult.value, 200);
  });

  adminAuthRouter.use("/session", middlewareManager.adminAuth);

  adminAuthRouter.get("/session", async (c) => {
    const adminSession = c.get("adminSession");

    return c.json(adminSession, 200);
  });

  adminAuthRouter.post("/logout", async (c) => c.json({ success: true }, 200));

  return adminAuthRouter;
};
