import {
  SegmentActionProperty,
  SegmentActionPropertyAttribute,
  SegmentAttribute,
  SegmentAttributeComparator,
} from "@komi-app/fans-sdk";
import { SelectOption } from "../types/select";

// TODO: add config service
const serverEndpoint = `http://localhost:3000`;

/**
 * Validates if the comparator is a range comparator
 * 
 * @param comparator The comparator to check
 * @returns If the comparator is a range comparator
 */
export const isRange = (comparator: SegmentAttributeComparator) => (
  comparator === SegmentAttributeComparator.Bt
  || comparator === SegmentAttributeComparator.Nbt
);

/**
 * Fetches the property values from the Komi server
 * 
 * @param {string} endpoint The Komi server endpoint to fetch from
 * @returns Fetched property values
 */
export const fetchPropValues = async (endpoint: string): Promise<string[]> => {
  const propertyValueEndpoint = `${serverEndpoint}${endpoint}`;
  const response = await fetch(
    propertyValueEndpoint,
    {
      // headers: mockHeaders,
    },
  );

  const json = await response.json();
  return json.payload;
};

/**
 * Gets the attribute by name from the attributes array
 * 
 * @param {string} name The name of the attribute to search
 * @param {SegmentAttribute[]} attributes The attributes to search
 * @returns The attribute with the given name
 */
export const getAttributeByName = (
  name: string,
  attributes: SegmentAttribute[],
): SegmentAttribute => {
  const attribute = attributes.find(attribute => attribute.name === name);
  if (!attribute) {
    throw new Error(`Attribute ${name} not found`);
  }

  return attribute;
};

/**
 * Converts the properties to options
 * 
 * @param {SegmentActionPropertyAttribute[]} properties The properties to convert
 * @returns Converted options from properties
 */
export const segmentAttributePropertiesToOptions = (
  properties: SegmentActionPropertyAttribute[],
) => (
  properties.map<SelectOption<SegmentActionProperty>>(
    ({ name }) => ({ label: name, value: name })
  )
);

/**
 * Converts the attributes to options
 * 
 * @param {SegmentAttribute[]} attributes The attributes to convert
 * @param {string} groupName The group name to use for the options
 * @returns The options converted from attributes
 */
export const segmentAttributesToOptions = (attributes: SegmentAttribute[], groupName?: string) => (
  attributes.map<SelectOption<SegmentAttribute>>((attribute) => ({
    groupName,
    label: attribute.name,
    value: attribute,
  }))
);
