import createLogger from "utils/logger";
import widgets from "widgets/widgets";

const logger = createLogger("validateWidgetData");

export default function validateWidgetData(widget, endpoint, data) {
  let valid = true;
  let dataParsed = data;
  let error;
  let mapping;
  const mappings = widgets[widget.type]?.mappings;
  if (mappings) {
    mapping = Object.values(mappings).find((m) => m.endpoint === endpoint);
  }

  if (mapping?.allowEmpty && Buffer.isBuffer(data) && data.length === 0) return true;

  if (Buffer.isBuffer(data)) {
    try {
      dataParsed = JSON.parse(data);
    } catch (e) {
      try {
        // try once more stripping whitespace
        dataParsed = JSON.parse(data.toString().replace(/\s/g, ""));
      } catch (e2) {
        error = e || e2;
        valid = false;
      }
    }
  }

  if (dataParsed && Object.entries(dataParsed).length) {
    mapping?.validate?.forEach((key) => {
      if (dataParsed[key] === undefined) {
        valid = false;
      }
    });
  }

  if (!valid) {
    logger.error(
      `Invalid data for widget '${widget.type}' endpoint '${endpoint}':\nExpected:${mapping?.validate}\nParse error: ${
        error ?? "none"
      }\nData: ${JSON.stringify(data)}`,
    );
  }

  return valid;
}
