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

const quoteNarrativeSchema = z
  .object({
    quoteNarrative: z.string().optional().nullable(),
  })
  .strict();

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

    const item = await opportunities.fetchRecord(identifier);
    const quoteNarrative = await item.updateQuoteNarrative(
      body.quoteNarrative ?? null
    );

    const response = apiResponse.successful(
      "Quote narrative saved successfully!",
      {
        quoteNarrative,
      }
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["sales.opportunity.update"] })
);
