import { Hono } from "hono";
import type { AppEnv } from "./types";
import { apiError } from "./lib/errors";
import { siteAuth } from "./middleware/auth";
import { activateRateLimit, rateLimit } from "./middleware/rate-limit";
import { sites } from "./routes/sites";
import { snapshots } from "./routes/snapshots";
import { storage } from "./routes/storage";
import { usage } from "./routes/usage";

const app = new Hono<AppEnv>();

app.get("/", (c) => c.json({ ok: true, service: "wp-back-api" }));

app.use("/v1/sites/activate", activateRateLimit);
app.route("/v1/sites", sites);

app.use("/v1/storage/*", siteAuth, rateLimit);
app.route("/v1/storage", storage);

app.use("/v1/snapshots/*", siteAuth, rateLimit);
app.use("/v1/snapshots", siteAuth, rateLimit);
app.route("/v1/snapshots", snapshots);

app.use("/v1/usage", siteAuth, rateLimit);
app.route("/v1/usage", usage);

app.notFound((c) => apiError(c, 404, "not_found", "Route not found"));
app.onError((err, c) => {
  console.error("unhandled error", err);
  return apiError(c, 500, "internal", "Internal error");
});

export default app;
