// Pure helpers for summarizing a connection's state in the UI. No DB writes,
// no side effects — easy to unit-test.

import { hasAllRequiredSecrets } from './connections.js';

/**
 * Reduce a connection shape to a UI-friendly status.
 *
 * Status values:
 *   - 'connected'   — installed=1 AND all required secrets present
 *   - 'reconnect'   — installed=1 but a required secret was revoked → broken
 *   - 'needs_setup' — installed=0 (initial state)
 *
 * @param {object} connection — shape from getConnection / listConnections
 * @returns {{
 *   status: 'connected' | 'reconnect' | 'needs_setup',
 *   label: string,
 *   tone: 'ready' | 'warn' | 'danger',
 *   footer: string | null,
 * }}
 */
export function summarizeConnection(connection) {
  if (!connection) {
    return { status: 'needs_setup', label: 'Not connected', tone: 'danger', footer: null };
  }
  if (!connection.installed) {
    return { status: 'needs_setup', label: 'Not connected', tone: 'danger', footer: null };
  }
  if (!hasAllRequiredSecrets(connection)) {
    return {
      status: 'reconnect',
      label: 'Reconnect',
      tone: 'warn',
      footer: 'A required credential was revoked.',
    };
  }
  return {
    status: 'connected',
    label: 'Connected',
    tone: 'ready',
    footer: formatFooter(connection),
  };
}

function formatFooter(connection) {
  const parts = [];
  if (connection.account_label) parts.push(connection.account_label);
  if (connection.settings?.last_4) parts.push(`••• ${connection.settings.last_4}`);
  if (connection.last_verified_at) {
    parts.push(`verified ${formatRelative(connection.last_verified_at)}`);
  }
  return parts.length ? parts.join(' · ') : null;
}

function formatRelative(iso) {
  try {
    const then = new Date(iso).getTime();
    const now = Date.now();
    const diff = Math.max(0, now - then);
    const minutes = Math.round(diff / 60000);
    if (minutes < 1) return 'just now';
    if (minutes < 60) return `${minutes}m ago`;
    const hours = Math.round(minutes / 60);
    if (hours < 24) return `${hours}h ago`;
    const days = Math.round(hours / 24);
    return `${days}d ago`;
  } catch {
    return '';
  }
}

/**
 * Extract a last-4 fingerprint from a credential value, redacting the rest.
 * Used by verify handlers to build a non-sensitive summary for the install row.
 *
 * Returns null if the value is too short to safely fingerprint.
 */
export function fingerprintLast4(value) {
  if (typeof value !== 'string') return null;
  const trimmed = value.trim();
  if (trimmed.length < 8) return null; // refuse to fingerprint tiny strings
  return trimmed.slice(-4);
}
