import { userAgent } from "next/server";
import { logger } from "@formbricks/logger";
import { ZId } from "@formbricks/types/common";
import { TContactAttributesInput } from "@formbricks/types/contact-attribute";
import { ResourceNotFoundError, ValidationError } from "@formbricks/types/errors";
import { TJsPersonState } from "@formbricks/types/js";
import { RequestBodyTooLargeError, parseJsonBodyWithLimit } from "@/app/lib/api/request-body";
import { responses } from "@/app/lib/api/response";
import { THandlerParams, withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { MAX_CONTACT_ATTRIBUTES_PER_REQUEST } from "@/lib/constants";
import { getOrganizationIdFromWorkspaceId } from "@/lib/utils/helper";
import { NULL_BYTE_REASON, hasNullByte } from "@/lib/utils/postgres-text";
import { resolveClientApiIds } from "@/lib/utils/resolve-client-id";
import { getIsContactsEnabled } from "@/modules/ee/license-check/lib/utils";
import { updateUser } from "./lib/update-user";

const handleError = (err: unknown, url: string): { response: Response; error?: unknown } => {
  if (err instanceof ResourceNotFoundError) {
    return { response: responses.notFoundResponse(err.resourceType, err.resourceId) };
  }

  if (err instanceof ValidationError) {
    return { response: responses.badRequestResponse(err.message, undefined, true) };
  }

  logger.error({ error: err, url }, "Error in POST /api/v1/client/[workspaceId]/user");
  return {
    response: responses.internalServerErrorResponse("Unable to fetch user state", true),
    error: err,
  };
};

type TContactUserRequestBody = Record<string, unknown> & {
  attributes?: Record<string, unknown>;
  userId?: unknown;
};

/** The parsed body, or the error response for a body that is too large or malformed. */
const readUserRequestBody = async (
  req: Request
): Promise<{ jsonInput: TContactUserRequestBody } | { response: Response }> => {
  try {
    return { jsonInput: await parseJsonBodyWithLimit<TContactUserRequestBody>(req) };
  } catch (error) {
    if (error instanceof RequestBodyTooLargeError) {
      return {
        response: responses.payloadTooLargeResponse("Payload Too Large", { error: error.message }, true),
      };
    }

    return {
      response: responses.badRequestResponse(
        "Malformed JSON input, please check your request body",
        { error: error instanceof Error ? error.message : "Unknown error occurred" },
        true
      ),
    };
  }
};

/** Why the attributes are rejected (array, too many keys, malformed email), or null when they pass. */
const getAttributesError = (attributes: Record<string, unknown> | undefined): string | null => {
  if (Array.isArray(attributes)) {
    return "attributes must be an object";
  }

  if (attributes && Object.keys(attributes).length > MAX_CONTACT_ATTRIBUTES_PER_REQUEST) {
    return `A request may set at most ${MAX_CONTACT_ATTRIBUTES_PER_REQUEST} attributes`;
  }

  if (attributes && Object.hasOwn(attributes, "email")) {
    const email = attributes.email;
    if (typeof email !== "string" || !email.includes("@") || email.length < 3) {
      return "Invalid email format";
    }
  }

  return null;
};

/** The userId and attributes of the request body, or the error response that rejects it. */
const parseUserRequestBody = async (
  req: Request
): Promise<{ userId: string; attributes: Record<string, unknown> | undefined } | { response: Response }> => {
  const body = await readUserRequestBody(req);
  if ("response" in body) {
    return body;
  }
  const { jsonInput } = body;

  // Basic input validation without Zod overhead
  if (
    !jsonInput ||
    typeof jsonInput !== "object" ||
    !jsonInput.userId ||
    typeof jsonInput.userId !== "string"
  ) {
    return {
      response: responses.badRequestResponse("userId is required and must be a string", undefined, true),
    };
  }

  if (hasNullByte(jsonInput.userId)) {
    return { response: responses.badRequestResponse(`userId ${NULL_BYTE_REASON}`, undefined, true) };
  }

  // Simple email validation if present (avoid Zod)
  const attributes =
    typeof jsonInput.attributes === "object" && jsonInput.attributes !== null
      ? jsonInput.attributes
      : undefined;

  const attributesError = getAttributesError(attributes);
  if (attributesError) {
    return { response: responses.badRequestResponse(attributesError, undefined, true) };
  }

  return { userId: jsonInput.userId, attributes };
};

export const OPTIONS = async (): Promise<Response> => {
  return responses.successResponse(
    {},
    true,
    // Cache CORS preflight responses for 1 hour (conservative approach)
    // Balances performance gains with flexibility for CORS policy changes
    "public, s-maxage=3600, max-age=3600"
  );
};

export const POST = withV1ApiWrapper({
  handler: async ({ req, props }: THandlerParams<{ params: Promise<{ workspaceId: string }> }>) => {
    const params = await props.params;

    try {
      // Basic type check for workspaceId
      if (typeof params.workspaceId !== "string") {
        return {
          response: responses.badRequestResponse("Workspace ID is required", undefined, true),
        };
      }

      const idParam = params.workspaceId.trim();

      // Validate CUID format
      const cuidValidation = ZId.safeParse(idParam);
      if (!cuidValidation.success) {
        logger.warn(
          {
            workspaceId: params.workspaceId,
            url: req.url,
            validationError: cuidValidation.error.issues[0]?.message,
          },
          "Invalid CUID format detected"
        );
        return {
          response: responses.badRequestResponse("Invalid workspace ID format", undefined, true),
        };
      }

      // Resolve: accepts a workspaceId
      const resolved = await resolveClientApiIds(idParam);
      if (!resolved) {
        return {
          response: responses.notFoundResponse("Workspace", idParam),
        };
      }
      const { workspaceId } = resolved;

      const parsed = await parseUserRequestBody(req);
      if ("response" in parsed) {
        return parsed;
      }
      const { userId, attributes } = parsed;

      const organizationId = await getOrganizationIdFromWorkspaceId(workspaceId);
      const isContactsEnabled = await getIsContactsEnabled(organizationId);
      if (!isContactsEnabled) {
        return {
          response: responses.forbiddenResponse(
            "User identification is only available for enterprise users.",
            true
          ),
        };
      }

      let attributeUpdatesToSend: TContactAttributesInput | null = null;
      if (attributes) {
        // remove userId and id from attributes
        const { userId: _userId, id: _id, ...updatedAttributes } = attributes;
        attributeUpdatesToSend = updatedAttributes as TContactAttributesInput;
      }

      const { device } = userAgent(req);
      const deviceType = device ? "phone" : "desktop";

      const {
        state: userState,
        messages,
        errors,
      } = await updateUser(workspaceId, userId, deviceType, attributeUpdatesToSend ?? undefined);

      // Build response (simplified structure)
      const responseJson: { state: TJsPersonState; messages?: string[]; errors?: string[] } = {
        state: userState,
        ...(messages && messages.length > 0 && { messages }),
        ...(errors && errors.length > 0 && { errors }),
      };

      return {
        response: responses.successResponse(responseJson, true),
      };
    } catch (err) {
      return handleError(err, req.url);
    }
  },
});
