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";
import { prisma } from "../../../../../constants";
import { z } from "zod";

// Helper to resolve member from DB
async function resolveMember(identifier: string | null | undefined) {
  if (!identifier) return null;
  const member = await prisma.cwMember.findFirst({ where: { identifier } });
  return member
    ? {
        id: member.id,
        identifier: member.identifier,
        name: `${member.firstName} ${member.lastName}`.trim(),
        cwMemberId: member.cwMemberId,
      }
    : { id: null, identifier, name: identifier, cwMemberId: null };
}

/* PATCH /v1/sales/opportunities/opportunity/:identifier/notes/:noteId */
export default createRoute(
  "patch",
  ["/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 body = await c.req.json();

    const schema = z
      .object({
        text: z.string().min(1).optional(),
        flagged: z.boolean().optional(),
      })
      .refine((d) => d.text !== undefined || d.flagged !== undefined, {
        message: "At least one of 'text' or 'flagged' must be provided",
      });

    const data = schema.parse(body);

    const item = await opportunities.fetchRecord(identifier);
    const updated = await item.updateNote(noteId, data);

    const response = apiResponse.successful(
      "Opportunity note updated successfully!",
      {
        id: updated.id,
        text: updated.text,
        type: updated.type
          ? { id: updated.type.id, name: updated.type.name }
          : null,
        flagged: updated.flagged,
        enteredBy: await resolveMember(updated.enteredBy),
      }
    );

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