import { readDocument, readMergedDocument, writeScope } from "./store.js";
import { resolveScope } from "./resolve.js";
export function createConfigStore(options) {
    const env = options.env ?? {};
    return {
        scope(definition) {
            return {
                async get(key) {
                    const resolved = await resolveScopedValues(options, definition, env);
                    return resolved[key];
                },
                async getAll() {
                    return resolveScopedValues(options, definition, env);
                },
                async set(key, value) {
                    const document = await readDocument(options.fs, options.filePath);
                    const currentValues = getOwnRecordEntry(document, definition.scope);
                    await writeScope(options.fs, options.filePath, definition.scope, {
                        ...currentValues,
                        [key]: value
                    });
                }
            };
        }
    };
}
async function resolveScopedValues(options, definition, env) {
    const document = await readMergedDocument(options.fs, options.filePath, options.projectFilePath);
    return resolveScope(definition.schema, getOwnRecordEntry(document, definition.scope), env);
}
function getOwnRecordEntry(record, key) {
    const value = Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;
    return value !== null && typeof value === "object" && !Array.isArray(value)
        ? value
        : {};
}
