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

const CONFIG_DIR = path.join(__dirname, '..', 'config');

function ensureDir() {
  if (!fs.existsSync(CONFIG_DIR)) {
    fs.mkdirSync(CONFIG_DIR, { recursive: true });
  }
}

function getStoreCachePath(profileId = 'shared') {
  return path.join(CONFIG_DIR, `${profileId}-stores-cache.json`);
}

function sanitizeStoreList(stores) {
  return Array.isArray(stores) ? stores.filter(Boolean) : [];
}

function readStoresCache(profileId) {
  ensureDir();
  const filePath = getStoreCachePath(profileId);
  if (!fs.existsSync(filePath)) {
    return null;
  }

  try {
    const parsed = readJsonFile(
      filePath,
      null,
      (value) =>
        value === null ||
        (
          value &&
          typeof value === 'object' &&
          !Array.isArray(value) &&
          Array.isArray(value.data) &&
          Number.isFinite(Number(value.fetchedAt))
        )
    );
    if (!parsed) {
      return null;
    }
    return {
      data: sanitizeStoreList(parsed.data),
      fetchedAt: Number(parsed.fetchedAt)
    };
  } catch (error) {
    console.error(`[STORE-CACHE] Konnte Cache fuer ${profileId} nicht lesen:`, error.message);
    return null;
  }
}

function writeStoresCache(profileId, storesCache) {
  if (!profileId || !storesCache) {
    return null;
  }
  const payload = {
    data: sanitizeStoreList(storesCache.data),
    fetchedAt: Number(storesCache.fetchedAt) || Date.now()
  };
  const filePath = getStoreCachePath(profileId);
  writeJsonFile(filePath, payload);
  return payload;
}

module.exports = {
  readStoresCache,
  writeStoresCache,
  getStoreCachePath
};
