import { createRoute } from "../../../modules/api-utils/createRoute";
import { opportunities } from "../../../managers/opportunities";
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/sales/opportunities */
export default createRoute(
  "get",
  ["/opportunities"],
  async (c) => {
    const page = Number(c.req.query("page") ?? 1);
    const rpp = Number(c.req.query("rpp") ?? 30);
    const search = c.req.query("search") as string;
    const includeClosed = c.req.query("includeClosed") === "true";

    const data = search
      ? await opportunities.search(search, page, rpp, { includeClosed })
      : await opportunities.fetchPages(page, rpp, { includeClosed });

    const totalRecords = search
      ? await opportunities.searchCount(search, { includeClosed })
      : await opportunities.count({ openOnly: !includeClosed });

    const gatedData = await Promise.all(
      data.map((item) =>
        processObjectValuePerms(
          item.toJson(),
          "obj.opportunity",
          c.get("user"),
        ),
      ),
    );

    const response = apiResponse.successful(
      "Opportunities fetched successfully!",
      gatedData,
      {
        pagination: {
          previousPage: page <= 1 ? null : page - 1,
          currentPage: page,
          nextPage: page >= totalRecords / rpp ? null : page + 1,
          totalPages: Math.ceil(totalRecords / rpp),
          totalRecords,
          listedRecords: rpp,
        },
      },
    );

    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["sales.opportunity.fetch.many"] }),
);
