// Shared label vocabulary for Stellen (Bewerbungen + Jobangebote).
//
// Labels describe the work-location character of a position. Several labels may
// be set per Stelle. They are stored as a JSON array string in the `labels`
// column and exposed as a string[] through the web UI and the REST API.

const LABEL_OPTIONS = [
  'Regional',
  'Remote-Deutschlandweit',
  'Homeoffice-Deutschlandweit',
];

// Normalize any incoming labels value (array, JSON string, comma-separated
// string, or a single label) into a clean, de-duplicated array limited to
// LABEL_OPTIONS and returned in canonical order for stable output.
function parseLabels(raw) {
  if (raw == null || raw === '') return [];
  let arr;
  if (Array.isArray(raw)) {
    arr = raw;
  } else if (typeof raw === 'string') {
    const s = raw.trim();
    if (!s) return [];
    if (s[0] === '[') {
      try { arr = JSON.parse(s); } catch (e) { arr = []; }
      if (!Array.isArray(arr)) arr = [];
    } else {
      arr = s.split(',');
    }
  } else {
    return [];
  }
  const chosen = new Set(
    arr.map((v) => String(v).trim()).filter((v) => LABEL_OPTIONS.includes(v))
  );
  return LABEL_OPTIONS.filter((l) => chosen.has(l));
}

// Canonical JSON string for storage in the DB (always a valid array).
function serializeLabels(raw) {
  return JSON.stringify(parseLabels(raw));
}

module.exports = { LABEL_OPTIONS, parseLabels, serializeLabels };
