import app from "../../data_stores.app.mjs";
export default {
  key: "data_stores-add-update-multiple-records",
  name: "Add or update multiple records",
  description: "Add or update multiple records to your [Pipedream Data Store](https://pipedream.com/data-stores/).",
  version: "0.0.8",
  annotations: {
    destructiveHint: true,
    openWorldHint: true,
    readOnlyHint: false,
  },
  type: "action",
  props: {
    app,
    dataStore: {
      propDefinition: [
        app,
        "dataStore",
      ],
    },
    data: {
      label: "Data",
      type: "object",
      description: "Enter data you'd like to add as key-value pairs, or reference an object from a previous step using a custom expression (e.g., `{{steps.data.$return_value}}`). Note that any keys that are duplicated will get overwritten with the last value entered (so `[{jerry: \"constanza\", jerry: \"seinfeld\"}]` will get stored as `[{jerry: \"seinfeld\"}]`).",
    },
    ttl: {
      propDefinition: [
        app,
        "ttl",
      ],
    },
  },
  methods: {
    
    convertString(value) {
      
      const primitives = [
        "boolean",
        "number",
      ];
      if (primitives.includes(typeof value)) {
        return value;
      }
      
      if (typeof value === "string") {
        
        if (value.toLowerCase() === "true") {
          return true;
        }
        if (value.toLowerCase() === "false") {
          return false;
        }
        
        if (!isNaN(value)) {
          return parseFloat(value);
        }
      }
      return this.app.evaluate(value);
    },
    
    populateHashMapOfData(data, map) {
      if (!Array.isArray(data) && typeof(data) === "object") {
        Object.keys(data).forEach((key) => map[key] = this.convertString(data[key]));
        return;
      }
      if (Array.isArray(data)) {
        for (const item of data) {
          this.populateHashMapOfData(item, map);
        }
      }
    },
    getHashMapOfData(data) {
      const map = {};
      this.populateHashMapOfData(data, map);
      return map;
    },
  },
  async run({ $ }) {
    if (typeof this.data === "string") {
      this.data = this.app.evaluate(this.data);
    }
    const map = this.getHashMapOfData(this.data);
    const keys = Object.keys(map);
    const promises = Object.keys(map).map((key) => {
      if (this.ttl) {
        return this.dataStore.set(key, map[key], {
          ttl: this.ttl,
        });
      } else {
        return this.dataStore.set(key, map[key]);
      }
    });
    await Promise.all(promises);
    if (keys.length === 0) {
      $.export("$summary", "No data was added to the data store.");
    } else {
      
      $.export("$summary", `Successfully added or updated ${keys.length} record${keys.length === 1 ? "" : "s"}${this.ttl ? ` (expires in ${this.app.formatTtl(this.ttl)})` : ""}`);
    }
    
    return {
      ...map,
      _ttl: this.ttl || null,
    };
  },
};