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 { getSalesOpportunityMetricsForMember, getSalesOpportunityMetricsAll } from "../../../modules/cache/salesOpportunityMetricsCache";
import { prisma } from "../../../constants";

/* GET /v1/sales/opportunities/metrics */
export default createRoute(
  "get",
  ["/opportunities/metrics"],
  async (c) => {
    const user = c.get("user");
    const scope = c.req.query("scope");
    const identifierOverride = c.req.query("identifier");

    // scope=all — return metrics for all active members (requires permission)
    if (scope === "all") {
      if (!(await user.hasPermission("sales.opportunity.metrics.all"))) {
        return c.json({ status: 403, message: "Forbidden", successful: false }, 403);
      }
      const allMetrics = await getSalesOpportunityMetricsAll();
      const response = apiResponse.successful(
        "Sales opportunity metrics fetched successfully!",
        allMetrics,
      );
      return c.json(response, response.status as ContentfulStatusCode);
    }

    // Determine which CW identifier to look up
    let cwIdentifier: string | null = null;

    if (identifierOverride) {
      if (!(await user.hasPermission("sales.opportunity.metrics.identifier.override"))) {
        return c.json({ status: 403, message: "Forbidden", successful: false }, 403);
      }
      cwIdentifier = identifierOverride;
    } else {
      const dbUser = await prisma.user.findFirst({
        where: { id: user.id },
        select: { cwIdentifier: true },
      });
      cwIdentifier = dbUser?.cwIdentifier ?? null;
    }

    if (!cwIdentifier) {
      const response = apiResponse.successful(
        "Sales opportunity metrics fetched successfully!",
        null,
      );
      return c.json(response, response.status as ContentfulStatusCode);
    }

    const metrics = await getSalesOpportunityMetricsForMember(cwIdentifier);
    const response = apiResponse.successful(
      "Sales opportunity metrics fetched successfully!",
      metrics,
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["sales.opportunity.fetch.many"] }),
);
