function normalizeText(value) {
  return typeof value === 'string' ? value.trim() : '';
}

function uniqueLines(lines) {
  const seen = new Set();

  return (Array.isArray(lines) ? lines : [])
    .map((line) => normalizeText(line))
    .filter((line) => {
      if (!line || seen.has(line)) {
        return false;
      }
      seen.add(line);
      return true;
    });
}

export function getPolicySnapshot(booking) {
  if (!booking || typeof booking !== 'object') {
    return {};
  }

  const snapshot = booking.policy_snapshot;
  return snapshot && typeof snapshot === 'object' ? snapshot : {};
}

export function getActionPolicy(booking, action) {
  const snapshot = getPolicySnapshot(booking);
  const key = normalizeText(action).toLowerCase();
  const policy = key && snapshot[key] && typeof snapshot[key] === 'object' ? snapshot[key] : {};

  return {
    allowed: policy.allowed !== false,
    summary: normalizeText(policy.summary),
    detailSummary: normalizeText(policy.detail_summary),
    why: normalizeText(policy.why),
    next: normalizeText(policy.next),
    cutoffLabel: normalizeText(policy.cutoff_label),
    windowLabel: normalizeText(policy.window_label),
    policyText: normalizeText(policy.policy_text)
  };
}

export function getPolicyStatusLines(booking) {
  const snapshot = getPolicySnapshot(booking);

  return uniqueLines([
    snapshot.status_message,
    snapshot.cancel?.detail_summary,
    snapshot.reschedule?.detail_summary
  ]);
}

export function getOutcomeModel(payload) {
  const outcome = payload && typeof payload === 'object' && payload.outcome && typeof payload.outcome === 'object'
    ? payload.outcome
    : {};

  return {
    title: normalizeText(outcome.title),
    summary: normalizeText(outcome.summary),
    details: uniqueLines([
      ...(Array.isArray(outcome.details) ? outcome.details : []),
      outcome.payment_summary
    ])
  };
}
