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

/* POST /v1/sales/opportunities/opportunity/:identifier/refresh */
export default createRoute(
  "post",
  ["/opportunities/opportunity/:identifier/refresh"],
  async (c) => {
    const identifier = c.req.param("identifier");
    const item = await opportunities.fetchItem(identifier);

    const refreshed = await item.refreshFromCW();

    const response = apiResponse.successful(
      "Opportunity refreshed from ConnectWise successfully!",
      refreshed.toJson(),
    );

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