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";

/* GET /v1/sales/opportunities/opportunity/:identifier/products */
export default createRoute(
  "get",
  ["/opportunities/opportunity/:identifier/products"],
  async (c) => {
    const identifier = c.req.param("identifier");
    const item = await opportunities.fetchRecord(identifier);

    const data = await item.fetchProducts();

    const response = apiResponse.successful(
      "Opportunity products fetched successfully!",
      data.map((p) => p.toJson()),
    );

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