let UtilError = require('./UtilError');

const applyApplicationIds = (document, template) => {
    if (template && template.systemHeader && template.systemHeader.applicationIds) {
        document.systemHeader.applicationIds = template.systemHeader.applicationIds;
    }
};

const belongsToApplicationTag = (doc, user) => {
    return !user.tagApplicationId
        || user.tagApplicationId === doc.systemHeader.tagApplicationId;
};

const belongsToApplicationBranch = (doc, user) => {
    return !user.branchApplicationId ||
        (doc.systemHeader.branchApplicationIds
            && doc.systemHeader.branchApplicationIds.some(appId => user.branchApplicationId === appId));
};

const belongsToApplication = (doc, user) => {
    return !user.applicationId
        || (doc.systemHeader.applicationIds
            && doc.systemHeader.applicationIds.some(appId => user.applicationId === appId));
};

const checkDocumentApplication = (doc, user) => {
    if (!belongsToApplication(doc, user)) {
        let errMessage = `Document ${doc.documentId} doesn't belong to user's selected applicationId: ${user.applicationId}`;
        logger.error(errMessage);
        throw UtilError.createForbiddenError(doc, SharedConstants.OPERATION_TYPE_READ);
    }

    if (!belongsToApplicationTag(doc, user)) {
        let errMessage = `Document ${doc.documentId} doesn't belong to user's selected tagApplicationId: ${user.tagApplicationId}`;
        logger.error(errMessage);
        throw UtilError.createForbiddenError(doc, SharedConstants.OPERATION_TYPE_READ);
    }

    if (!belongsToApplicationBranch(doc, user)) {
        let errMessage = `Document ${doc.documentId} doesn't belong to user's selected branchApplicationId: ${user.applicationId}`;
        logger.error(errMessage);
        throw UtilError.createForbiddenError(doc, SharedConstants.OPERATION_TYPE_READ);
    }
};

module.exports = {
    applyApplicationIds: applyApplicationIds,
    checkDocumentApplication: checkDocumentApplication
};