import { createRoute } from "../../../modules/api-utils/createRoute";
import { unifiSites } from "../../../managers/unifiSites";
import { apiResponse } from "../../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../../middleware/authorization";
import { processObjectValuePerms } from "../../../modules/permission-utils/processObjectPermissions";

/* GET /v1/unifi/sites */
export default createRoute(
  "get",
  ["/sites"],
  async (c) => {
    const sites = await unifiSites.fetchAll();

    const gatedData = await Promise.all(
      sites.map((site) =>
        processObjectValuePerms(site, "obj.unifiSite", c.get("user")),
      ),
    );

    const response = apiResponse.successful(
      "UniFi Sites Fetched Successfully!",
      gatedData,
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["unifi.access", "unifi.sites.fetch.many"] }),
);
