import { createRoute } from "../../../../modules/api-utils/createRoute";
import { apiResponse } from "../../../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../../../middleware/authorization";
import { opportunities } from "../../../../managers/opportunities";
import { activityCw } from "../../../../modules/cw-utils/activities/activities";
import { OptimaType } from "../../../../workflows/wf.opportunity";

/* GET /v1/sales/opportunities/opportunity/:identifier/activities */
export default createRoute(
  "get",
  ["/opportunities/opportunity/:identifier/activities"],
  async (c) => {
    const identifier = c.req.param("identifier");

    const opportunity = await opportunities.fetchItem(identifier);

    const rawActivities = await activityCw.fetchByOpportunityDirect(
      opportunity.cwOpportunityId,
    );

    // Return only open workflow activities (status != 2)
    const openActivities = rawActivities
      .filter((a: any) => a.status?.id !== 2)
      .map((a: any) => {
        const optimaTypeField = a.customFields?.find(
          (f: any) => f.id === OptimaType.FIELD_ID || f.caption === "Optima_Type",
        );
        const parentActivityField = a.customFields?.find(
          (f: any) => f.id === 50 || f.caption === "Parent_Activity",
        );
        return {
          cwActivityId: a.id,
          name: a.name,
          optimaType: optimaTypeField?.value ?? null,
          parentActivityId: parentActivityField?.value
            ? parseInt(parentActivityField.value, 10) || null
            : null,
          status: a.status,
          dateStart: a.dateStart ?? null,
          dateEnd: a.dateEnd ?? null,
        };
      });

    const response = apiResponse.successful("Open activities fetched.", {
      activities: openActivities,
    });
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["sales.opportunity.view"] }),
);
