// Decides how a dynamic ad attribute should be shaped for a given render context.
// context: 'add_edit' -> ad create/edit form (exact single value per attribute)
//          'filter'    -> search filter panel (may render as a from/to range)

export type AttributeContext = "add_edit" | "filter";

export const parseMultiSelectValue = (raw: any): string[] => {
  if (Array.isArray(raw)) return raw;
  if (typeof raw === "string" && raw !== "") {
    try {
      const parsed = JSON.parse(raw);
      return Array.isArray(parsed) ? parsed : [];
    } catch (e) {
      return [];
    }
  }
  return [];
};

// Normalizes any truthy/falsy representation of a boolean attribute into '1' / '0' / ''.
export const parseBooleanValue = (raw: any): string => {
  if (raw === true || raw === 1 || raw === "1" || raw === "true") return "1";
  if (raw === false || raw === 0 || raw === "0" || raw === "false") return "0";
  return "";
};

// A 'select' attribute is rendered as a from/to range ONLY in the filter context,
// and only when the attribute definition was flagged range_filterable (e.g. تعداد اتاق).
export const isRangeInFilterContext = (attribute: any, context: AttributeContext): boolean => {
  if (context !== "filter") return false;
  if (["range", "range_price", "range_number"].includes(attribute?.type)) return true;
  return attribute?.type === "select" && !!attribute?.range_filterable;
};

/**
 * Normalizes a raw attribute (as returned by /attribute or /admin/attribute) into the
 * shape the templates expect for the given context, optionally merging an existing
 * in-memory attribute (e.g. previously entered form values on ad edit).
 */
export const normalizeAttributeForContext = (
  attribute: any,
  context: AttributeContext,
  existing: any = null
) => {
  const values = attribute.values
    ? attribute.values.map((v: any) => (typeof v === "string" ? { title: v, value: v } : v))
    : [];

  if (isRangeInFilterContext(attribute, context)) {
    return {
      ...attribute,
      values,
      min_value: existing?.min_value ?? "",
      max_value: existing?.max_value ?? "",
    };
  }

  if (attribute.type === "multi_select") {
    return {
      ...attribute,
      values,
      selected_values: parseMultiSelectValue(existing?.selected_values ?? existing?.value ?? attribute.value),
    };
  }

  if (attribute.type === "single_boolean_select") {
    return {
      ...attribute,
      values,
      value: parseBooleanValue(existing?.value ?? attribute.value),
    };
  }

  return {
    ...attribute,
    values,
    value: existing?.value ?? attribute.value ?? "",
  };
};

export function useAttributeRenderer() {
  return {
    parseMultiSelectValue,
    parseBooleanValue,
    isRangeInFilterContext,
    normalizeAttributeForContext,
  };
}
