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 GenericError from "../../../../Errors/GenericError";

/* DELETE /v1/sales/opportunities/opportunity/:identifier */
export default createRoute(
  "delete",
  ["/opportunities/opportunity/:identifier"],
  async (c) => {
    const identifier = c.req.param("identifier");

    try {
      await opportunities.deleteItem(identifier);

      const response = apiResponse.successful(
        "Opportunity deleted successfully!",
      );

      return c.json(response, response.status as ContentfulStatusCode);
    } catch (err) {
      const isAxios =
        err != null && typeof err === "object" && "isAxiosError" in err;

      if (isAxios) {
        const axiosErr = err as any;
        const cwStatus: number = axiosErr.response?.status ?? 502;
        const cwMessage: string =
          axiosErr.response?.data?.message ??
          "Failed to delete the opportunity in ConnectWise";

        return c.json(
          {
            status: cwStatus,
            message: cwMessage,
            error: "ConnectWiseDeleteError",
            successful: false,
            meta: { timestamp: Date.now() },
          },
          cwStatus as ContentfulStatusCode,
        );
      }

      throw err;
    }
  },
  authMiddleware({ permissions: ["sales.opportunity.delete"] }),
);
