import { Hono } from "hono";
import type { AppConfig } from "../config.js";
import { MiddlewareManager } from "../middlewares/middleware.js";
import type { BaseEnv } from "../types/app.types.js";
import { getAuthenticatedRouter } from "./authRouter.js";
import { getMaybeAuthenticatedRouter } from "./maybeAuthRouter.js";
import { getPublicRouter } from "./public.js";
import { getStripeWebhookRouter } from "./stripe.js";
import { getTaskRouter } from "./tasks.js";

export const getMainRouter = (config: AppConfig) => {
  const mainRouter = new Hono<BaseEnv>();

  const middlewareManager = MiddlewareManager.getInstance();

  // Apply supabase middleware globally (needed by all routes)
  mainRouter.use(middlewareManager.supabase);

  // Apply remaining middlewares after public routes
  mainRouter.use(middlewareManager.streamChat);
  mainRouter.use(middlewareManager.r2);
  mainRouter.use(middlewareManager.transporter);
  mainRouter.use(middlewareManager.stripe);
  mainRouter.use(middlewareManager.stripeSync);

  // public routes
  mainRouter.route("/public", getPublicRouter());

  // tasks routes
  mainRouter.route("/tasks", getTaskRouter());

  // webhooks
  mainRouter.route("/stripe-webhook", getStripeWebhookRouter());

  // maybe authenticated routes (checked first to allow unauthenticated booking)
  mainRouter.route("/", getMaybeAuthenticatedRouter());

  // authenticated routes
  mainRouter.route("/", getAuthenticatedRouter(config));

  return mainRouter;
};

/**
 * Type-safe API routes for RPC usage
 * Use with hono/client: const client = hc<ApiRoutes>('http://localhost:8080')
 */
export type ApiRoutes = ReturnType<typeof getMainRouter>;
