'use strict';

const path = require('path');
const fs = require('fs');
const FileBackend = require('../backends/FileBackend');

const BASE_DIR = path.resolve(__dirname, '../../../datasets/assetData');
// Files in datasets/assetData that aren't editor menu trees.
const EXCLUDE = ['assetData', 'monsterSamples', 'unitData'];

// Plain per-id File backend, but the menu namespace also wants to key by the
// inner `softwareType` field (so '/menu/rotatingmachine' works even if the
// file is named machine.json). The FileBackend gives us filename-keyed maps;
// we rekey in a thin wrapper.
const backend = new FileBackend({
    baseDir: BASE_DIR,
    layout: 'per-id',
    caseInsensitive: true,
    exclude: EXCLUDE,
});

// Menu trees are looked up by softwareType. We index by BOTH the inner
// `softwareType` field AND the filename (sans .json), because consumers come
// from two paths: editor endpoints pass the node type ('rotatingmachine'),
// while older code paths pass the filename slug ('machine'). Both should hit
// the same tree.
function _rekeyBySoftwareType(map) {
    const out = new Map();
    for (const [filenameId, data] of map.entries()) {
        const stKey = String(data?.softwareType || '').toLowerCase();
        const fnKey = String(filenameId).toLowerCase();
        if (stKey) out.set(stKey, data);
        if (fnKey && fnKey !== stKey) out.set(fnKey, data);
    }
    return out;
}

module.exports = {
    name: 'menu',
    description: 'Editor cascade trees (supplier→type→model→unit), keyed by softwareType',
    loadAll: () => _rekeyBySoftwareType(backend.loadAll()),
    refresh: async () => _rekeyBySoftwareType(await backend.refresh()),
    // Exposed for inline tests / debugging.
    _BASE_DIR: BASE_DIR,
    _EXCLUDE: EXCLUDE,
    _existsForFilename: (id) => fs.existsSync(path.join(BASE_DIR, `${id}.json`)),
};
