import { ConditionNode } from "@/lib/api/dataflow";

/**
 * 고유 ID 생성 함수
 */
export const generateConditionId = (): string => {
  return `cond_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
};

/**
 * 그룹 ID 생성 함수
 */
export const generateGroupId = (): string => {
  return `group_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
};

/**
 * 액션 그룹 ID 생성 함수
 */
export const generateActionGroupId = (): string => {
  return `action_group_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
};

/**
 * 열린 그룹 찾기
 */
export const findOpenGroups = (conditions: ConditionNode[]) => {
  const openGroups: Array<{ groupId: string; groupLevel: number }> = [];

  for (const condition of conditions) {
    if (condition.type === "group-start") {
      openGroups.push({
        groupId: condition.groupId!,
        groupLevel: condition.groupLevel!,
      });
    } else if (condition.type === "group-end") {
      // 해당 그룹 제거
      const groupIndex = openGroups.findIndex((g) => g.groupId === condition.groupId);
      if (groupIndex !== -1) {
        openGroups.splice(groupIndex, 1);
      }
    }
  }

  return openGroups;
};

/**
 * 다음 그룹 레벨 계산
 */
export const getNextGroupLevel = (conditions: ConditionNode[]): number => {
  const openGroups = findOpenGroups(conditions);
  return openGroups.length;
};

/**
 * 현재 조건의 그룹 레벨 계산
 */
export const getCurrentGroupLevel = (conditions: ConditionNode[], conditionIndex: number): number => {
  let level = 0;
  for (let i = 0; i < conditionIndex; i++) {
    const condition = conditions[i];
    if (condition.type === "group-start") {
      level++;
    } else if (condition.type === "group-end") {
      level--;
    }
  }
  return level;
};

/**
 * 조건부 연결인지 확인하는 헬퍼 함수
 */
export const isConditionalConnection = (connectionType: string): boolean => {
  return connectionType === "data-save" || connectionType === "external-call";
};

/**
 * 데이터 타입에 따른 입력 타입 결정
 */
export const getInputTypeForDataType = (dataType: string): "text" | "number" | "datetime-local" | "date" | "time" => {
  const lowerDataType = dataType?.toLowerCase() || "string";

  if (lowerDataType.includes("timestamp") || lowerDataType.includes("datetime")) {
    return "datetime-local";
  } else if (lowerDataType.includes("date")) {
    return "date";
  } else if (lowerDataType.includes("time")) {
    return "time";
  } else if (
    lowerDataType.includes("int") ||
    lowerDataType.includes("numeric") ||
    lowerDataType.includes("decimal") ||
    lowerDataType.includes("float") ||
    lowerDataType.includes("double")
  ) {
    return "number";
  } else {
    return "text";
  }
};
