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 { 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 };
}

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

    const schema = z.object({
      text: z.string().min(1, "Note text is required"),
      flagged: z.boolean().optional(),
    });

    const data = schema.parse(body);

    const item = await opportunities.fetchRecord(identifier);
    const user = c.get("user");

    const created = await item.addNote(data.text, user.login, {
      flagged: data.flagged,
    });

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

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