/**
 * IndexedDB Service for SIF-GT Offline Storage
 * Provides local database functionality for offline operation
 */

class IndexedDBService {
  constructor() {
    this.dbName = 'SIF_GT_DB';
    this.version = 1;
    this.db = null;
  }

  /**
   * Initialize the IndexedDB database with all required stores
   */
  async init() {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.version);

      request.onerror = () => {
        reject(new Error('Error opening IndexedDB'));
      };

      request.onsuccess = (event) => {
        this.db = event.target.result;
        resolve(this.db);
      };

      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        
        // Create auth store
        if (!db.objectStoreNames.contains('auth')) {
          const authStore = db.createObjectStore('auth', { keyPath: 'key' });
        }

        // Create proyectos store
        if (!db.objectStoreNames.contains('proyectos')) {
          const proyectosStore = db.createObjectStore('proyectos', { keyPath: 'id' });
          proyectosStore.createIndex('nombreProyecto', 'nombreProyecto', { unique: false });
          proyectosStore.createIndex('fechaCreacion', 'fechaCreacion', { unique: false });
          proyectosStore.createIndex('usuarioId', 'usuarioId', { unique: false });
        }

        // Create rodales store
        if (!db.objectStoreNames.contains('rodales')) {
          const rodalesStore = db.createObjectStore('rodales', { keyPath: 'id' });
          rodalesStore.createIndex('proyectoId', 'proyectoId', { unique: false });
          rodalesStore.createIndex('nombreRodal', 'nombreRodal', { unique: false });
        }

        // Create especies store
        if (!db.objectStoreNames.contains('especies')) {
          const especiesStore = db.createObjectStore('especies', { keyPath: 'id' });
          especiesStore.createIndex('nombreCientifico', 'nombreCientifico', { unique: false });
          especiesStore.createIndex('nombreComun', 'nombreComun', { unique: false });
        }

        // Create registrosCampo store
        if (!db.objectStoreNames.contains('registrosCampo')) {
          const registrosStore = db.createObjectStore('registrosCampo', { keyPath: 'id' });
          registrosStore.createIndex('rodalId', 'rodalId', { unique: false });
          registrosStore.createIndex('estadoSincronizacion', 'estadoSincronizacion', { unique: false });
          registrosStore.createIndex('fechaCaptura', 'fechaCaptura', { unique: false });
          registrosStore.createIndex('usuarioId', 'usuarioId', { unique: false });
        }

        // Create syncQueue store for pending sync operations
        if (!db.objectStoreNames.contains('syncQueue')) {
          const syncStore = db.createObjectStore('syncQueue', { keyPath: 'id', autoIncrement: true });
          syncStore.createIndex('operation', 'operation', { unique: false });
          syncStore.createIndex('timestamp', 'timestamp', { unique: false });
          syncStore.createIndex('status', 'status', { unique: false });
        }
      };
    });
  }

  /**
   * Generic method to get a transaction for a store
   */
  getTransaction(storeName, mode = 'readonly') {
    if (!this.db) {
      throw new Error('Database not initialized');
    }
    return this.db.transaction([storeName], mode);
  }

  /**
   * Generic method to get an object store
   */
  getStore(storeName, mode = 'readonly') {
    const transaction = this.getTransaction(storeName, mode);
    return transaction.objectStore(storeName);
  }

  /**
   * Close the database connection
   */
  close() {
    if (this.db) {
      this.db.close();
      this.db = null;
    }
  }

  /**
   * Delete the entire database (for testing/reset purposes)
   */
  async deleteDatabase() {
    this.close();
    return new Promise((resolve, reject) => {
      const deleteRequest = indexedDB.deleteDatabase(this.dbName);
      deleteRequest.onsuccess = () => resolve();
      deleteRequest.onerror = () => reject(new Error('Error deleting database'));
    });
  }
}

// Create singleton instance
const indexedDBService = new IndexedDBService();

export default indexedDBService;