
// This service simulates a remote backend API.
// It uses a separate LocalStorage namespace ('_CLOUD_') to mimic a database.
// This proves that the app syncs data from 'App State' to 'Server State'.

const CLOUD_PREFIX = '_CLOUD_DB_';
const DELAY_MS = 600; // Simulate network latency

// Helper to get data from "Cloud"
const getCloudData = (collection: string) => {
    const data = localStorage.getItem(`${CLOUD_PREFIX}${collection}`);
    return data ? JSON.parse(data) : [];
};

// Helper to save data to "Cloud"
const setCloudData = (collection: string, data: any[]) => {
    localStorage.setItem(`${CLOUD_PREFIX}${collection}`, JSON.stringify(data));
};

export const api = {
    // Generic Fetch
    fetch: async (collection: string) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                const data = getCloudData(collection);
                console.log(`[API] Fetched ${collection} from server:`, data);
                resolve(data);
            }, DELAY_MS);
        });
    },

    // Create Item
    create: async (collection: string, item: any) => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (Math.random() > 0.98) { // Random 2% failure rate for realism
                    reject(new Error('Server Error: Connection timeout'));
                    return;
                }
                const currentData = getCloudData(collection);
                setCloudData(collection, [item, ...currentData]);
                console.log(`[API] Created item in ${collection}:`, item);
                resolve(item);
            }, DELAY_MS);
        });
    },

    // Update Item
    update: async (collection: string, item: any) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                const currentData = getCloudData(collection);
                const updatedData = currentData.map((d: any) => d.id === item.id ? item : d);
                setCloudData(collection, updatedData);
                console.log(`[API] Updated item in ${collection}:`, item);
                resolve(item);
            }, DELAY_MS);
        });
    },

    // Delete Item
    delete: async (collection: string, id: string) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                const currentData = getCloudData(collection);
                const updatedData = currentData.filter((d: any) => d.id !== id);
                setCloudData(collection, updatedData);
                console.log(`[API] Deleted item ${id} from ${collection}`);
                resolve(true);
            }, DELAY_MS);
        });
    },

    // Simulate Syncing Data (Batch)
    syncBatch: async (actions: any[]) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                console.log('[API] Processing Sync Batch:', actions);
                actions.forEach(action => {
                    const { collection, type, payload, id } = action;
                    const currentData = getCloudData(collection);
                    
                    if (type === 'CREATE') {
                        // Check if exists to avoid dupes
                        if (!currentData.find((d: any) => d.id === payload.id)) {
                            setCloudData(collection, [payload, ...currentData]);
                        }
                    } else if (type === 'UPDATE') {
                        setCloudData(collection, currentData.map((d: any) => d.id === payload.id ? payload : d));
                    } else if (type === 'DELETE') {
                        setCloudData(collection, currentData.filter((d: any) => d.id !== id));
                    }
                });
                resolve(true);
            }, DELAY_MS * 2);
        });
    }
};
