import Validator from './validator.js';
import { relationshipTypes } from '../jhipster/index.mjs';
import { relationshipTypeExists } from '../jhipster/relationship-types.js';
const { ONE_TO_ONE, MANY_TO_MANY, MANY_TO_ONE, ONE_TO_MANY } = relationshipTypes;
export default class RelationshipValidator extends Validator {
    constructor() {
        super('relationship', ['from', 'to', 'type']);
    }
    validate(jdlRelationship) {
        super.validate(jdlRelationship);
        checkType(jdlRelationship);
        checkInjectedFields(jdlRelationship);
        checkForRequiredReflexiveRelationship(jdlRelationship);
        checkRelationshipType(jdlRelationship);
    }
}
function checkType(jdlRelationship) {
    if (!relationshipTypeExists(jdlRelationship.type)) {
        throw new Error(`The relationship type '${jdlRelationship.type}' doesn't exist.`);
    }
}
function checkInjectedFields(jdlRelationship) {
    if (!(jdlRelationship.injectedFieldInFrom || jdlRelationship.injectedFieldInTo)) {
        throw new Error('At least one injected field is required.');
    }
}
function checkForRequiredReflexiveRelationship(jdlRelationship) {
    if (jdlRelationship.from.toLowerCase() === jdlRelationship.to.toLowerCase() &&
        (jdlRelationship.isInjectedFieldInFromRequired || jdlRelationship.isInjectedFieldInToRequired)) {
        throw new Error(`Required relationships to the same entity are not supported, for relationship from and to '${jdlRelationship.from}'.`);
    }
}
function checkRelationshipType(jdlRelationship) {
    switch (jdlRelationship.type) {
        case ONE_TO_ONE:
            checkOneToOneRelationship(jdlRelationship);
            break;
        case MANY_TO_ONE:
        case MANY_TO_MANY:
        case ONE_TO_MANY:
            return;
        default:
            throw new Error(`This case shouldn't have happened with type ${jdlRelationship.type}.`);
    }
}
function checkOneToOneRelationship(jdlRelationship) {
    if (!jdlRelationship.injectedFieldInFrom) {
        throw new Error(`In the One-to-One relationship from ${jdlRelationship.from} to ${jdlRelationship.to}, ` +
            'the source entity must possess the destination, or you must invert the direction of the relationship.');
    }
}
