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

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

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

function getStoreWatchPath(profileId = 'shared') {
  return path.join(STORE_WATCH_DIR, `${profileId}-store-watch.json`);
}

function sanitizeEntry(entry) {
  if (!entry || !entry.storeId) {
    return null;
  }
  const parsedLastCheck = Number(entry.lastStatusCheckAt);
  const normalized = {
    storeId: String(entry.storeId),
    storeName: entry.storeName ? String(entry.storeName).trim() : `Store ${entry.storeId}`,
    regionId: entry.regionId ? String(entry.regionId) : '',
    regionName: entry.regionName ? String(entry.regionName).trim() : '',
    lastTeamSearchStatus:
      entry.lastTeamSearchStatus === 1
        ? 1
        : entry.lastTeamSearchStatus === 0
        ? 0
        : null,
    lastStatusCheckAt: Number.isFinite(parsedLastCheck) ? parsedLastCheck : null
  };
  if (!normalized.regionId) {
    return null;
  }
  return normalized;
}

function readStoreWatch(profileId) {
  ensureDir();
  const filePath = getStoreWatchPath(profileId);
  if (!fs.existsSync(filePath)) {
    writeJsonFile(filePath, [], { backup: false });
    return [];
  }
  try {
    const parsed = readJsonFile(filePath, [], Array.isArray);
    if (!Array.isArray(parsed)) {
      return [];
    }
    const unique = new Map();
    parsed.forEach((entry) => {
      const sanitized = sanitizeEntry(entry);
      if (sanitized) {
        unique.set(sanitized.storeId, sanitized);
      }
    });
    return Array.from(unique.values());
  } catch (error) {
    console.error(`[STORE-WATCH] Konnte Datei ${filePath} nicht lesen:`, error.message);
    return [];
  }
}

function writeStoreWatch(profileId, entries = []) {
  const sanitized = [];
  const seen = new Set();
  entries.forEach((entry) => {
    const normalized = sanitizeEntry(entry);
    if (normalized && !seen.has(normalized.storeId)) {
      sanitized.push(normalized);
      seen.add(normalized.storeId);
    }
  });
  ensureDir();
  const filePath = getStoreWatchPath(profileId);
  writeJsonFile(filePath, sanitized);
  return sanitized;
}

function listWatcherProfiles() {
  ensureDir();
  return fs
    .readdirSync(STORE_WATCH_DIR)
    .filter((file) => file.endsWith('-store-watch.json'))
    .map((file) => file.replace(/-store-watch\.json$/, ''));
}

module.exports = {
  readStoreWatch,
  writeStoreWatch,
  listWatcherProfiles
};
