export function relTime(input?: string | Date | null): string {
  if (!input) return '—';
  const d = typeof input === 'string' ? new Date(input) : input;
  if (Number.isNaN(d.getTime())) return '—';
  const diffMin = Math.round((Date.now() - d.getTime()) / 60000);
  if (diffMin < 1) return 'Just now';
  if (diffMin < 60) return `${diffMin}m ago`;
  const diffHours = Math.round(diffMin / 60);
  if (diffHours < 24) return `${diffHours}h ago`;
  const diffDays = Math.round(diffHours / 24);
  if (diffDays === 1) return 'Yesterday';
  if (diffDays < 30) return `${diffDays}d ago`;
  return d.toLocaleDateString('en-IN', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  });
}

export function fmtDate(
  input?: string | Date | null,
  options: Intl.DateTimeFormatOptions = {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  },
): string {
  if (!input) return '—';
  const d = typeof input === 'string' ? new Date(input) : input;
  if (Number.isNaN(d.getTime())) return '—';
  return d.toLocaleDateString('en-IN', options);
}

const FIELD_LABELS: Record<string, string> = { name: 'Name', phone: 'Phone', city: 'City', adminName: 'Admin name', adminEmail: 'Admin email' };
const asText = (v: unknown) => (v === null || v === undefined || v === '' ? '—' : String(v));

/** Turns a platform audit entry's metadata into one readable sentence for tables. */
export function describeAuditDetails(action: string, metadata: Record<string, unknown> | null | undefined): string {
  if (!metadata) return '—';
  const m = metadata;
  switch (action) {
    case 'CREATE_ORG':
      return `Created with admin ${asText(m.adminName)} (${asText(m.adminEmail)})`;
    case 'SUSPEND_ORG':
    case 'UNSUSPEND_ORG':
    case 'UPDATE_ORG_STATUS':
      return `Status ${asText(m.previousStatus)} → ${asText(m.newStatus)}`;
    case 'INVITE_ORG_ADMIN':
      return `Invited ${asText(m.name)} (${asText(m.email)})`;
    case 'RESEND_ORG_ADMIN_INVITE':
      return `Resent invitation to ${asText(m.name)} (${asText(m.email)})`;
    case 'UPDATE_ORG_PROFILE': {
      const previous = (m.previous ?? {}) as Record<string, unknown>;
      const updated = (m.updated ?? {}) as Record<string, unknown>;
      const changes = Object.keys(updated).map((k) => `${FIELD_LABELS[k] ?? k}: ${asText(previous[k])} → ${asText(updated[k])}`);
      return changes.length ? changes.join('; ') : 'No changes';
    }
    default:
      return Object.entries(m)
        .filter(([, v]) => typeof v !== 'object')
        .map(([k, v]) => `${FIELD_LABELS[k] ?? k}: ${asText(v)}`)
        .join('; ');
  }
}

export const AUDIT_ACTION_LABELS: Record<string, string> = {
  CREATE_ORG: 'Organization created',
  UPDATE_ORG_PROFILE: 'Profile updated',
  SUSPEND_ORG: 'Organization suspended',
  UNSUSPEND_ORG: 'Organization reactivated',
  INVITE_ORG_ADMIN: 'Admin invited',
  RESEND_ORG_ADMIN_INVITE: 'Invitation resent',
};

/** Human-readable name for an audit action code, falling back to the code itself. */
export function auditActionLabel(action: string): string {
  return AUDIT_ACTION_LABELS[action] ?? action;
}
