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 { z } from "zod";

/* PATCH /v1/sales/opportunities/opportunity/:identifier/products/sequence */
export default createRoute(
  "patch",
  ["/opportunities/opportunity/:identifier/products/sequence"],
  async (c) => {
    const identifier = c.req.param("identifier");
    const body = await c.req.json();

    const schema = z.object({
      orderedIds: z
        .array(z.number().int().positive())
        .min(1, "At least one forecast item ID is required"),
    });

    const { orderedIds } = schema.parse(body);

    const item = await opportunities.fetchRecord(identifier);
    const updated = await item.resequenceProducts(orderedIds);

    const response = apiResponse.successful(
      "Product sequence updated successfully!",
      {
        products: updated.map((p) => p.toJson()),
      },
    );

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