File size: 1,761 Bytes
ba95018
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
 * Template Data Loader
 * ====================
 * Fetches the template structure from the protected backend API.
 * This file replaces the original templateData.js — the actual data
 * lives on the server and is only accessible to authenticated users.
 */

const API_BASE = import.meta.env.VITE_API_URL || '';

// In-memory cache so we only fetch once per session
let _cachedData = null;

/**
 * Fetches the complete template data from the backend.
 * Must be called after authentication (needs Bearer token).
 */
export async function fetchTemplateData(token) {
  if (_cachedData) return _cachedData;

  const res = await fetch(`${API_BASE}/api/template`, {
    headers: { Authorization: `Bearer ${token}` },
  });

  if (!res.ok) {
    throw new Error('Failed to load template data');
  }

  _cachedData = await res.json();
  return _cachedData;
}

/**
 * Returns cached template data (must call fetchTemplateData first).
 */
export function getTemplateData() {
  return _cachedData;
}

// Provide empty defaults for imports that happen before fetch completes.
// These get replaced once fetchTemplateData() resolves.
export let ABBREVIATIONS = [];
export let SMART_PHRASES = [];
export let HEADER_FIELDS = [];

// Default export — the sections array
let TEMPLATE_SECTIONS = [];
export default TEMPLATE_SECTIONS;

/**
 * Called after fetchTemplateData resolves to populate the module-level exports.
 */
export function hydrateTemplateData(data) {
  TEMPLATE_SECTIONS = data.sections || [];
  ABBREVIATIONS = data.abbreviations || [];
  SMART_PHRASES = data.smartPhrases || [];
  HEADER_FIELDS = data.headerFields || [];
  _cachedData = data;

  // Return for convenience
  return { TEMPLATE_SECTIONS, ABBREVIATIONS, SMART_PHRASES, HEADER_FIELDS };
}