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/user/:id */
export default createRoute(
  "get",
  ["/opportunities/user/:id"],
  async (c) => {
    const userId = c.req.param("id");
    const includeClosed = c.req.query("includeClosed") === "true";

    const data = await opportunities.fetchByUser(userId, { includeClosed });

    const response = apiResponse.successful(
      "Opportunities fetched successfully!",
      data.map((item) => item.toJson()),
    );

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