import path from 'path';
import { applicationTypes } from '../jhipster/index.mjs';
import { toFilePath, readJSONFile } from '../readers/json-file-reader.js';
import { doesFileExist } from '../utils/file-utils.js';
let configuration = {};
export default function exportEntities(passedConfiguration) {
    init(passedConfiguration);
    if (configuration.entities.length === 0) {
        return configuration.entities;
    }
    const subFolder = passedConfiguration.application.forSeveralApplications ? configuration.application.name : '';
    configuration.entities = updateEntities(subFolder);
    if (shouldFilterOutEntitiesBasedOnMicroservice()) {
        configuration.entities = filterOutEntitiesByMicroservice();
    }
    return configuration.entities;
}
function init(passedConfiguration) {
    if (!passedConfiguration || !passedConfiguration.entities) {
        throw new Error('Entities have to be passed to be exported.');
    }
    configuration = passedConfiguration;
}
function updateEntities(subFolder) {
    return configuration.entities.map(entity => {
        const filePath = path.join(subFolder, toFilePath(entity.name));
        return updateEntityToGenerateWithExistingOne(filePath, entity);
    });
}
function updateEntityToGenerateWithExistingOne(filePath, entity) {
    if (doesFileExist(filePath)) {
        const fileOnDisk = readJSONFile(filePath);
        if (!entity.annotations?.changelogDate && fileOnDisk?.annotations?.changelogDate) {
            entity.annotations = entity.annotations || {};
            entity.annotations.changelogDate = fileOnDisk.annotations.changelogDate;
            return { ...fileOnDisk, ...entity };
        }
    }
    return entity;
}
function shouldFilterOutEntitiesBasedOnMicroservice() {
    return (configuration.application.type && configuration.application.type === applicationTypes.MICROSERVICE && configuration.application.name);
}
function filterOutEntitiesByMicroservice() {
    return configuration.entities.filter(entity => {
        return !(entity.microserviceName && entity.microserviceName.toLowerCase() !== configuration.application.name.toLowerCase());
    });
}
