type MessageRecord = Record<string, any>;

export class MessageUtils {
  static validateMessage(message: unknown): message is MessageRecord {
    return Boolean(
      message &&
        typeof message === "object" &&
        (message as MessageRecord).type,
    );
  }

  static formatMessage(
    type: string,
    content: unknown,
    options: MessageRecord = {},
  ): MessageRecord {
    return {
      type,
      content,
      timestamp: Date.now(),
      ...options,
    };
  }

  static isCompleteMessage(message: MessageRecord | null | undefined): boolean {
    return Boolean(message && message.isComplete === true);
  }

  static isPongMessage(messageData: unknown): boolean {
    if (typeof messageData === "string") {
      return (
        messageData === "pong" || messageData.toLowerCase().includes("pong")
      );
    }
    if (typeof messageData === "object" && messageData !== null) {
      return (messageData as MessageRecord).type === "pong";
    }
    return false;
  }

  static safeParseJSON(messageStr: string): MessageRecord | null {
    try {
      return JSON.parse(messageStr);
    } catch {
      console.warn("JSON parse failed:", messageStr);
      return null;
    }
  }

  static createTypewriterMessage(
    content: string,
    isComplete = false,
    type = "typewriter",
  ): MessageRecord {
    return {
      type,
      content,
      isComplete,
      timestamp: Date.now(),
    };
  }

  static createLoadingMessage(content = "loading..."): MessageRecord {
    return {
      type: "loading",
      content,
      timestamp: Date.now(),
    };
  }

  static createErrorMessage(error: Error | string): MessageRecord {
    return {
      type: "error",
      content: error instanceof Error ? error.message : error || "Unknown Error",
      timestamp: Date.now(),
    };
  }
}
