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

    if (isNaN(noteId))
      throw new GenericError({
        status: 400,
        name: "InvalidNoteId",
        message: "Note ID must be a number",
      });

    const item = await opportunities.fetchRecord(identifier);
    await item.deleteNote(noteId);

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

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