import { db, PendingOperation } from './db';
import { inventoryApi } from './api';

export const syncOfflineOperations = async (userId: number) => {
  const pending = await db.pendingOperations
    .filter(op => op.synced === 0)
    .toArray();

  if (pending.length === 0) return { success: 0, errors: 0 };

  try {
    // Format operations for the backend (convert timestamp to ISO string if needed)
    const formattedOps = pending.map(op => ({
      type: op.type,
      barcode: op.barcode,
      quantity: op.quantity,
      timestamp: new Date(op.timestamp).toISOString(),
      uuid: op.uuid,
      details: op.details
    }));

    const results = await inventoryApi.syncBulkOperations(userId, formattedOps);

    // Mark successfully synced operations in IndexedDB
    // For simplicity, if the whole bulk call succeeds, we mark all as synced or delete them
    // Real implementation should match success/error per item
    
    const successBarcodes = new Set(results.success.map((s: any) => s.barcode));
    
    for (const op of pending) {
      if (successBarcodes.has(op.barcode)) {
        await db.pendingOperations.update(op.id!, { synced: 1 });
        // Or remove it: await db.pendingOperations.delete(op.id!);
      }
    }

    // Clean up synced operations
    await db.pendingOperations.where('synced').equals(1).delete();

    return { 
      success: results.success.length, 
      errors: results.errors.length,
      details: results
    };
  } catch (error) {
    console.error('Sync failed:', error);
    throw error;
  }
};

export const fetchAndCacheItems = async () => {
  try {
    const items = await inventoryApi.getItems();
    // Update local cache
    await db.items.clear();
    await db.items.bulkPut(items);
    return items;
  } catch (error) {
    console.error('Failed to fetch items, using cache:', error);
    return await db.items.toArray();
  }
};
