import { createRoute } from "../../../modules/api-utils/createRoute";
import { unifiSites } from "../../../managers/unifiSites";
import { companies } from "../../../managers/companies";
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/company/companies/:identifier/unifi/sites */
export default createRoute(
  "get",
  ["/companies/:identifier/unifi/sites"],
  async (c) => {
    const company = await companies.fetch(c.req.param("identifier"));
    const sites = await unifiSites.fetchByCompany(company.id);

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

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