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

    const data = await opportunities.fetchByUser(user.id, { 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"] }),
);
