const fs = require('fs');
const path = require('path');
const defaultConfig = require('../data/defaultConfig');
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 getConfigPath(profileId = 'shared') {
  return path.join(CONFIG_DIR, `${profileId}-pickup-config.json`);
}

function hydrateConfigFile(profileId) {
  ensureDir();
  const filePath = getConfigPath(profileId);
  if (!fs.existsSync(filePath)) {
    writeJsonFile(filePath, defaultConfig, { backup: false });
  }
  return filePath;
}

function readConfig(profileId) {
  const filePath = hydrateConfigFile(profileId);
  try {
    const parsed = readJsonFile(filePath, defaultConfig, Array.isArray);
    return Array.isArray(parsed) ? parsed : [];
  } catch (err) {
    console.error(`Failed to read config for ${profileId}:`, err);
    return [];
  }
}

function writeConfig(profileId, payload) {
  const filePath = hydrateConfigFile(profileId);
  writeJsonFile(filePath, payload);
  return filePath;
}

module.exports = {
  readConfig,
  writeConfig,
  getConfigPath
};
