export interface AttributeFilter {
  key: string;
  value?: string;
}

const KEY_REGEX = /^[a-zA-Z0-9._-]+$/;

/** Parses a single `?attr=` URL value. Returns null for invalid / blank input. */
export function parseAttrParam(raw: string): AttributeFilter | null {
  if (!raw) return null;
  const trimmed = raw.trim();
  if (trimmed.length === 0) return null;

  const colon = trimmed.indexOf(':');
  if (colon < 0) {
    return KEY_REGEX.test(trimmed) ? { key: trimmed } : null;
  }

  const key = trimmed.substring(0, colon).trim();
  const value = raw.substring(raw.indexOf(':') + 1);
  if (!KEY_REGEX.test(key)) return null;
  return { key, value };
}

/** Serialises an AttributeFilter back to a URL `?attr=` value. */
export function formatAttrParam(f: AttributeFilter): string {
  return f.value === undefined ? f.key : `${f.key}:${f.value}`;
}

const FACET_REGEX = /^\s*([a-zA-Z0-9._-]+)\s*:\s*(\S(?:.*\S)?)\s*$/;

/** Parses a cmd-k query like `order: 47` into a facet descriptor. */
export function parseFacetQuery(query: string): AttributeFilter | null {
  const m = FACET_REGEX.exec(query);
  if (!m) return null;
  return { key: m[1], value: m[2] };
}
