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

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

const DEFAULT_PREFERENCES = {
  location: null
};

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

function getPreferencesPath(profileId = 'shared') {
  return path.join(PREF_DIR, `${profileId}-preferences.json`);
}

function sanitizeLocation(location) {
  if (!location) {
    return null;
  }
  const lat = Number(location.lat);
  const lon = Number(location.lon);
  if (!Number.isFinite(lat) || !Number.isFinite(lon)) {
    return null;
  }
  if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {
    return null;
  }
  return {
    lat,
    lon,
    updatedAt: Date.now()
  };
}

function readPreferences(profileId) {
  ensureDir();
  const filePath = getPreferencesPath(profileId);
  if (!fs.existsSync(filePath)) {
    writeJsonFile(filePath, DEFAULT_PREFERENCES, { backup: false });
    return { ...DEFAULT_PREFERENCES };
  }
  try {
    const parsed = readJsonFile(
      filePath,
      DEFAULT_PREFERENCES,
      (value) => value && typeof value === 'object' && !Array.isArray(value)
    );
    return {
      location: sanitizeLocation(parsed.location) || null
    };
  } catch (error) {
    console.error(`[PREFERENCES] Konnte Datei ${filePath} nicht lesen:`, error.message);
    return { ...DEFAULT_PREFERENCES };
  }
}

function writePreferences(profileId, patch = {}) {
  const current = readPreferences(profileId);
  const next = {
    location:
      patch.location === undefined
        ? current.location
        : sanitizeLocation(patch.location)
  };
  ensureDir();
  const filePath = getPreferencesPath(profileId);
  writeJsonFile(filePath, next);
  return next;
}

module.exports = {
  readPreferences,
  writePreferences,
  sanitizeLocation
};
