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

const CONFIG_DIR = path.join(__dirname, '..', 'config');
const IMAGE_ROOT = path.join(CONFIG_DIR, 'journal-images');

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

function ensureBaseDirs() {
  ensureDir(CONFIG_DIR);
  ensureDir(IMAGE_ROOT);
}

function getJournalPath(profileId = 'shared') {
  return path.join(CONFIG_DIR, `${profileId}-pickup-journal.json`);
}

function getProfileImageDir(profileId = 'shared') {
  return path.join(IMAGE_ROOT, String(profileId));
}

function hydrateJournalFile(profileId) {
  ensureBaseDirs();
  const filePath = getJournalPath(profileId);
  if (!fs.existsSync(filePath)) {
    writeJsonFile(filePath, [], { backup: false });
  }
  return filePath;
}

function readJournal(profileId) {
  const filePath = hydrateJournalFile(profileId);
  try {
    const parsed = readJsonFile(filePath, [], Array.isArray);
    return Array.isArray(parsed) ? parsed : [];
  } catch (error) {
    console.error(`[JOURNAL] Konnte Journal für ${profileId} nicht lesen:`, error.message);
    return [];
  }
}

function writeJournal(profileId, entries = []) {
  const filePath = hydrateJournalFile(profileId);
  writeJsonFile(filePath, entries);
  return filePath;
}

function saveJournalImage(profileId, { id, filename, buffer }) {
  ensureBaseDirs();
  const profileDir = getProfileImageDir(profileId);
  ensureDir(profileDir);
  const safeName = filename.replace(/[^a-zA-Z0-9_.-]/g, '_');
  const filePath = path.join(profileDir, safeName);
  fs.writeFileSync(filePath, buffer);
  return {
    id,
    filename: safeName,
    filePath
  };
}

function deleteJournalImage(profileId, filename) {
  if (!filename) {
    return;
  }
  const filePath = path.join(getProfileImageDir(profileId), filename);
  if (fs.existsSync(filePath)) {
    fs.unlinkSync(filePath);
  }
}

module.exports = {
  readJournal,
  writeJournal,
  saveJournalImage,
  deleteJournalImage,
  getProfileImageDir
};
