/**
 * db_server.js
 * بديل window.DB يتواصل مع السيرفر بدل IndexedDB
 * يُستخدم لمشاركة البيانات بين أجهزة متعددة على الشبكة
 */

(function() {
  'use strict';

  const API_BASE = window.location.origin + '/api';

  async function apiCall(method, store, id, body) {
    let url = API_BASE + '/' + store;
    if (id !== undefined && id !== null) url += '/' + id;
    
    const opts = {
      method,
      headers: { 'Content-Type': 'application/json' }
    };
    if (body !== undefined) opts.body = JSON.stringify(body);
    
    const resp = await fetch(url, opts);
    if (!resp.ok) throw new Error('Server error: ' + resp.status);
    
    const text = await resp.text();
    return text ? JSON.parse(text) : null;
  }

  window.DB = {
    /**
     * Get all records from a store
     */
    getAll: function(storeName) {
      return apiCall('GET', storeName);
    },

    /**
     * Get single record by id
     */
    get: function(storeName, id) {
      return apiCall('GET', storeName, id);
    },

    /**
     * Add a record (id auto-assigned if missing)
     */
    add: function(storeName, record) {
      return apiCall('POST', storeName, null, record);
    },

    /**
     * Update an existing record
     */
    update: function(storeName, record) {
      if (!record.id) return apiCall('POST', storeName, null, record);
      return apiCall('PUT', storeName, record.id, record);
    },

    /**
     * Remove a record by id
     */
    remove: function(storeName, id) {
      return apiCall('DELETE', storeName, id);
    },

    /**
     * Clear all records in a store
     */
    clear: function(storeName) {
      return apiCall('DELETE', storeName, '_all');
    }
  };

  console.log('✅ DB connected to server at:', API_BASE);

  // Health check
  fetch(API_BASE + '/users').then(r => {
    if (r.ok) {
      console.log('✅ Server connection OK');
    }
  }).catch(e => {
    console.warn('⚠️ Server not reachable, falling back is disabled. Please start server.js');
  });

})();
