const fs = require('fs');
const path = require('path');
const { readJsonFile, writeJsonFile } = require('./jsonFileStore');

const STORE_STATUS_FILE = path.join(__dirname, '..', 'config', 'store-watch-status.json');

function ensureDir() {
  const dir = path.dirname(STORE_STATUS_FILE);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
}

function readStoreStatus() {
  ensureDir();
  if (!fs.existsSync(STORE_STATUS_FILE)) {
    writeJsonFile(STORE_STATUS_FILE, {}, { backup: false });
    return {};
  }
  try {
    const parsed = readJsonFile(
      STORE_STATUS_FILE,
      {},
      (value) => value && typeof value === 'object' && !Array.isArray(value)
    );
    if (parsed && typeof parsed === 'object') {
      return parsed;
    }
    return {};
  } catch (error) {
    console.error('[STORE-STATUS] Konnte Cache nicht lesen:', error.message);
    return {};
  }
}

function writeStoreStatus(cache = {}) {
  ensureDir();
  writeJsonFile(STORE_STATUS_FILE, cache);
}

module.exports = {
  readStoreStatus,
  writeStoreStatus
};
