
import { SalesRecord } from '../types';

const DB_NAME = 'CrazeAnalytixDB';
const STORE_NAME = 'salesData';
const ADS_STORE_NAME = 'adsData';
const DB_VERSION = 2;
// Increment this when data processing logic changes (e.g., field mapping changes)
// This forces cache invalidation and re-processing of CSV data
const DATA_SCHEMA_VERSION = 2; // Updated for LICENSE column mapping

const initDB = (): Promise<IDBDatabase> => {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, DB_VERSION);

    request.onupgradeneeded = (event) => {
      const db = (event.target as IDBOpenDBRequest).result;
      if (!db.objectStoreNames.contains(STORE_NAME)) {
        db.createObjectStore(STORE_NAME);
      }
      if (!db.objectStoreNames.contains(ADS_STORE_NAME)) {
        db.createObjectStore(ADS_STORE_NAME);
      }
    };

    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
};

export const saveSalesData = async (data: SalesRecord[]): Promise<void> => {
  try {
    const db = await initDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction(STORE_NAME, 'readwrite');
      const store = transaction.objectStore(STORE_NAME);

      // Store the data array
      store.put(data, 'currentData');
      // Store the timestamp
      store.put(new Date().toISOString(), 'lastUpdated');
      // Store schema version
      store.put(DATA_SCHEMA_VERSION, 'schemaVersion');

      transaction.oncomplete = () => resolve();
      transaction.onerror = () => reject(transaction.error);
    });
  } catch (error) {
    console.error("Error saving to IndexedDB:", error);
    // Fallback or silence error (data just won't be cached)
  }
};

export const loadSalesData = async (): Promise<{ data: SalesRecord[]; lastUpdated: string | null }> => {
  try {
    const db = await initDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction(STORE_NAME, 'readonly');
      const store = transaction.objectStore(STORE_NAME);

      const dataReq = store.get('currentData');
      const dateReq = store.get('lastUpdated');
      const versionReq = store.get('schemaVersion');

      transaction.oncomplete = () => {
        const cachedVersion = versionReq.result;

        // If schema version doesn't match, invalidate cache
        if (cachedVersion !== DATA_SCHEMA_VERSION) {
          console.log('[Storage] Schema version mismatch. Cached:', cachedVersion, 'Current:', DATA_SCHEMA_VERSION);
          resolve({
            data: [],
            lastUpdated: null
          });
          return;
        }

        resolve({
          data: dataReq.result || [],
          lastUpdated: dateReq.result || null
        });
      };

      transaction.onerror = () => reject(transaction.error);
    });
  } catch (error) {
    console.error("Error loading from IndexedDB:", error);
    return { data: [], lastUpdated: null };
  }
};

export const clearSalesData = async (): Promise<void> => {
  try {
    const db = await initDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction(STORE_NAME, 'readwrite');
      const store = transaction.objectStore(STORE_NAME);
      store.clear();
      transaction.oncomplete = () => resolve();
      transaction.onerror = () => reject(transaction.error);
    });
  } catch (e) {
    console.error(e);
  }
}

// --- ADS STORAGE ---

export const saveAdsData = async (data: any[]): Promise<void> => {
  try {
    const db = await initDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction(ADS_STORE_NAME, 'readwrite');
      const store = transaction.objectStore(ADS_STORE_NAME);

      store.put(data, 'currentData');
      store.put(new Date().toISOString(), 'lastUpdated');

      transaction.oncomplete = () => resolve();
      transaction.onerror = () => reject(transaction.error);
    });
  } catch (error) {
    console.error("Error saving ads to IndexedDB:", error);
  }
};

export const loadAdsData = async (): Promise<{ data: any[]; lastUpdated: string | null }> => {
  try {
    const db = await initDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction(ADS_STORE_NAME, 'readonly');
      const store = transaction.objectStore(ADS_STORE_NAME);

      const dataReq = store.get('currentData');
      const dateReq = store.get('lastUpdated');

      transaction.oncomplete = () => {
        resolve({
          data: dataReq.result || [],
          lastUpdated: dateReq.result || null
        });
      };

      transaction.onerror = () => reject(transaction.error);
    });
  } catch (error) {
    console.error("Error loading ads from IndexedDB:", error);
    return { data: [], lastUpdated: null };
  }
};

export const clearAdsData = async (): Promise<void> => {
  try {
    const db = await initDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction(ADS_STORE_NAME, 'readwrite');
      const store = transaction.objectStore(ADS_STORE_NAME);
      store.clear();
      transaction.oncomplete = () => resolve();
      transaction.onerror = () => reject(transaction.error);
    });
  } catch (e) {
    console.error(e);
  }
}
