// consistency.js
import { API_BASE_URL, CONSISTENCY_POLL_INTERVAL, setInconsistencyData, inconsistencyData } from './global.js';
import { hideConsistencyModal, showConsistencyModal } from './modals.js';
import { loadAllData } from './data_loader.js'; // Will be imported later
import { checkConsistency } from './global.js';
/**
* Core function to resolve consistency by making a POST call to a sync endpoint.
* @param {string} action - 'flush' (Cache -> DB) or 'rollback' (DB -> Cache).
*/
async function resolveConsistency(action) {
let url = '';
let message = '';
if (action === 'flush') {
url = `${API_BASE_URL}/flush-to-db`;
message = 'Flushing cache to DB...';
} else if (action === 'rollback') {
url = `${API_BASE_URL}/load-from-db`;
message = 'Rolling back cache from DB...';
} else {
return;
}
if (!confirm(`Are you sure you want to perform the action: ${action.toUpperCase()}? This will overwrite the target configuration.`)) {
return;
}
const modal = document.getElementById('consistencyModal');
if (modal) modal.style.display = 'none';
const button = document.getElementById('consistency-button');
if (button) {
button.textContent = message;
button.classList.remove('consistent', 'inconsistent', 'error');
button.classList.add('loading');
button.disabled = true;
}
try {
const response = await fetch(url, { method: 'POST' });
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`HTTP Error ${response.status}: ${errorBody}`);
}
alert(`Sync successful via ${action.toUpperCase()}. Reloading data.`);
loadAllData();
checkConsistency();
} catch (error) {
alert(`Failed to sync via ${action}. Check console for details.`);
console.error(`Sync operation (${action}) failed:`, error);
checkConsistency();
}
}
// Exported functions must be attached to 'window' if called from inline HTML attributes
export function manualFlush() {
resolveConsistency('flush');
}
export function manualRollback() {
resolveConsistency('rollback');
}