/**
 * Cache for draft audit creation.
 * Stores audit info and observations in sessionStorage so they persist across page navigations.
 * Used when user must fill info, save to cache, then add at least 2 observations before creating the audit.
 */

const CACHE_KEY = 'createAudit_draftObservations';
const AUDIT_INFO_CACHE_KEY = 'createAudit_draftInfo';

/**
 * Get all cached observations.
 * @returns {Array} Array of { form_id, form_title, answers }
 */
export const getCachedObservations = () => {
    try {
        const raw = sessionStorage.getItem(CACHE_KEY);
        if (!raw) return [];
        const parsed = JSON.parse(raw);
        return Array.isArray(parsed) ? parsed : [];
    } catch {
        return [];
    }
};

/**
 * Add an observation to the cache.
 * @param {Object} observation - { form_id, form_title, answers }
 */
export const addCachedObservation = (observation) => {
    const list = getCachedObservations();
    list.push({
        ...observation,
        _cachedAt: Date.now()
    });
    sessionStorage.setItem(CACHE_KEY, JSON.stringify(list));
};

/**
 * Remove an observation from the cache by index.
 * @param {number} index
 */
export const removeCachedObservation = (index) => {
    const list = getCachedObservations();
    list.splice(index, 1);
    sessionStorage.setItem(CACHE_KEY, JSON.stringify(list));
};

/**
 * Clear all cached observations (call after successful audit creation).
 */
export const clearCachedObservations = () => {
    sessionStorage.removeItem(CACHE_KEY);
};

// --- Audit information fields cache ---

/**
 * Save audit info to cache (auditor, audit name, country, location, work area, dates, coauditors, auditees).
 * @param {Object} auditInfo - Form data from CreateAudit
 */
export const setCachedAuditInfo = (auditInfo) => {
    try {
        sessionStorage.setItem(AUDIT_INFO_CACHE_KEY, JSON.stringify(auditInfo || {}));
    } catch {
        // ignore
    }
};

/**
 * Get cached audit info.
 * @returns {Object|null} Cached form data or null
 */
export const getCachedAuditInfo = () => {
    try {
        const raw = sessionStorage.getItem(AUDIT_INFO_CACHE_KEY);
        if (!raw) return null;
        return JSON.parse(raw);
    } catch {
        return null;
    }
};

/**
 * Clear cached audit info (call after successful audit creation or cancel).
 */
export const clearCachedAuditInfo = () => {
    sessionStorage.removeItem(AUDIT_INFO_CACHE_KEY);
};

/**
 * Clear all create-audit draft data (info + observations).
 */
export const clearAllCreateAuditCache = () => {
    clearCachedObservations();
    clearCachedAuditInfo();
};
