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/products/:productId */
export default createRoute(
  "delete",
  ["/opportunities/opportunity/:identifier/products/:productId"],
  async (c) => {
    const identifier = c.req.param("identifier");
    const productId = Number(c.req.param("productId"));

    if (!Number.isInteger(productId) || productId <= 0) {
      throw new GenericError({
        status: 400,
        name: "InvalidProductId",
        message: "productId must be a positive integer",
      });
    }

    const opportunity = await opportunities.fetchRecord(identifier);

    // Verify the forecast item exists before attempting deletion
    const products = await opportunity.fetchProducts();
    const product = products.find((item) => item.cwForecastId === productId);

    if (!product) {
      throw new GenericError({
        status: 404,
        name: "ForecastItemNotFound",
        message: `Forecast item ${productId} not found on opportunity`,
      });
    }

    try {
      await opportunity.deleteProduct(productId);

      const response = apiResponse.successful(
        "Product deleted from opportunity 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 product 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.product.delete"] }),
);
