import { basename, join } from 'path';
import { Duplex } from 'stream';
import { loadFile } from 'mem-fs';
import { Minimatch } from 'minimatch';
import { setModifiedFileState } from 'mem-fs-editor/state';
import { GENERATOR_JHIPSTER } from '../../generator-constants.mjs';
import { getJDLObjectFromSingleApplication } from '../../../jdl/converters/json-to-jdl-converter.js';
export const exportJDLTransform = ({ destinationPath, jdlStorePath, throwOnMissingConfig = true, keepEntitiesConfig, }) => Duplex.from(async function* (files) {
    const yoRcFilePath = join(destinationPath, '.yo-rc.json');
    const entitiesMatcher = new Minimatch(`${destinationPath}/.jhipster/*.json`);
    const entitiesFiles = [];
    const entitiesMap = new Map();
    let yoRcFileInMemory;
    let jdlStoreFileInMemory;
    for await (const file of files) {
        if (file.path === yoRcFilePath) {
            yoRcFileInMemory = file;
        }
        else if (file.path === jdlStorePath) {
            jdlStoreFileInMemory = file;
        }
        else if (file.contents && entitiesMatcher.match(file.path)) {
            entitiesMap.set(basename(file.path).replace('.json', ''), JSON.parse(file.contents.toString()));
            entitiesFiles.push(file);
        }
        else {
            yield file;
        }
    }
    const yoRcFile = loadFile(yoRcFilePath);
    const yoRcContents = yoRcFileInMemory?.contents ?? yoRcFile.contents;
    if (yoRcContents) {
        const contents = JSON.parse(yoRcContents.toString());
        if (contents[GENERATOR_JHIPSTER]?.jdlStore) {
            const { jdlStore, jwtSecretKey, rememberMeKey, jhipsterVersion, creationTimestamp, incrementalChangelog, ...rest } = contents[GENERATOR_JHIPSTER];
            const jdlObject = getJDLObjectFromSingleApplication({ ...contents, [GENERATOR_JHIPSTER]: { ...rest, incrementalChangelog } }, entitiesMap);
            const jdlContents = jdlObject.toString();
            const jdlStoreFile = jdlStoreFileInMemory ?? loadFile(jdlStorePath);
            jdlStoreFile.contents = Buffer.from(jdlContents);
            setModifiedFileState(jdlStoreFile);
            jdlStoreFile.conflicter = 'force';
            yield jdlStoreFile;
            yoRcFile.contents = Buffer.from(JSON.stringify({ [GENERATOR_JHIPSTER]: { jdlStore, jwtSecretKey, rememberMeKey, jhipsterVersion, creationTimestamp } }, null, 2));
            setModifiedFileState(yoRcFile);
            yoRcFile.conflicter = 'force';
            yield yoRcFile;
            if (keepEntitiesConfig || incrementalChangelog) {
                for (const file of entitiesFiles) {
                    yield file;
                }
            }
        }
        else if (throwOnMissingConfig) {
            throw new Error(`File ${yoRcFilePath} is not a valid JHipster configuration file`);
        }
    }
    else if (throwOnMissingConfig) {
        throw new Error(`File ${yoRcFilePath} has no contents`);
    }
});
