<%#
 Copyright 2013-2024 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<%- include('/liquibase-changelog-header') -%>
<%_ if (addedFields && addedFields.length) { _%>

    <!--
        Added columns to the entity <%= entity.entityClass %>.
    -->
    <changeSet id="<%= changelogDate %>-1-add-columns" author="jhipster">
        <addColumn tableName="<%= entity.entityTableName %>">
    <%_ for (field of addedFields) { _%>
            <column name="<%= (field.options && field.options.fieldColumnName) || field.columnName %>" type="<%= field.columnType %>"<%- this.createDefaultValueLiquibaseAttribute(field, true) -%><%- this.formatAsLiquibaseRemarks(field.documentation, true) %>/>
        <%_ if (field.shouldCreateContentType) { _%>
            <column name="<%= field.columnName %>_content_type" type="varchar(255)"/>
        <%_ }
    } // End for (field of addedFields) _%>
        </addColumn>
    <%_ for (field of addedFields) {
        if (field.shouldDropDefaultValue) { _%>
        <dropDefaultValue tableName="<%= entity.entityTableName %>" columnName="<%= field.columnName %>" columnDataType="${datetimeType}"/>
        <%_ } _%>
    <%_ } _%>
    </changeSet>
<%_ } _%>
<%_ if (removedFields && removedFields.length) { _%>

    <!--
        Dropped columns to the entity <%= entity.entityClass %>.
    -->
    <changeSet id="<%= changelogDate %>-1-drop-columns" author="jhipster">
        <dropColumn tableName="<%= entity.entityTableName %>">
    <%_ for (field of removedFields) { _%>
            <column name="<%= field.columnName %>"/>
    <%_ } _%>
        </dropColumn>
    </changeSet>
<%_ } _%>
<%_ if (addedRelationships && addedRelationships.length > 0) {
    let hasRelationShips = false;
    let hasJoinRelationShips = false;
    let hasRelationshipWithFieldUpdates = false;
    for (relationship of addedRelationships) {
        if (relationship.shouldWriteRelationship) {
            hasRelationShips = true;
        } else if (relationship.shouldWriteJoinTable) {
            hasJoinRelationShips = true;
        }

        // at least one relationship must update fields
        if (!relationshipsToRecreateForeignKeysOnly.includes(relationship)) {
            hasRelationshipWithFieldUpdates = true;
        }
    }
    if (hasRelationShips || hasJoinRelationShips) {
 _%>

    <!--
        Added relationships to the entity <%= entity.entityClass %>.
    -->
    <changeSet id="<%= changelogDate %>-1-add-relationships" author="jhipster">
        <%_ if (hasRelationShips && hasRelationshipWithFieldUpdates) { _%>
        <addColumn tableName="<%= entity.entityTableName %>">
            <%_
            for (relationship of addedRelationships) {
                if (relationship.shouldWriteRelationship && !relationshipsToRecreateForeignKeysOnly.includes(relationship)) {
                    for (const otherEntityPkField of relationship.otherEntity.primaryKey.fields) { _%>
                <column name="<%= relationship.columnName %>_<%= otherEntityPkField.columnName %>" type="<%= otherEntityPkField.columnType %>"/>
                    <%_ } _%>
                <%_ } _%>
            <%_ } _%>
        </addColumn>
        <% } %>
        <%_ const joinTableRelations = addedRelationships
                .filter(rel => rel.shouldWriteJoinTable)
                .filter(rel => !relationshipsToRecreateForeignKeysOnly.includes(rel));
            if(joinTableRelations.length > 0) {
        _%>
            <%_ for (relationship of joinTableRelations) { _%>

        <createTable tableName="<%= relationship.joinTable.name %>">
                <%_ for (field of relationship.otherEntity.primaryKey.fields) { _%>
            <column name="<%= relationship.columnName %>_<%= field.columnName %>" type="<%= field.columnType %>">
                <constraints nullable="false"/>
            </column>
                <%_ } _%>
                <%_ for (field of entity.primaryKey.fields) { _%>
            <column name="<%= entity.entityTableName %>_<%= field.columnName %>" type="<%= field.columnType %>">
                <constraints nullable="false"/>
            </column>
                <%_ } _%>
        </createTable>

        <addPrimaryKey columnNames="<%= entity.primaryKey.fields.map(field => `${entity.entityTableName}_${field.columnName}`).join(', ') %>, <%= relationship.otherEntity.primaryKey.fields.map(field => `${relationship.columnName}_${field.columnName}`).join(', ') %>" tableName="<%= relationship.joinTable.name %>"/>
            <%_ } _%>
        <%_ } _%>
    </changeSet>
    <%_ } _%>
<%_ } _%>
<%_
/* ======== Start removed relationships exists ======== */
if (removedRelationships && removedRelationships.length) {
    let hasRelationShips = false;
    let hasJoinRelationShips = false;
    let hasRelationshipWithFieldUpdates = false;
    for (relationship of removedRelationships) {
        if (relationship.shouldWriteRelationship) {
            hasRelationShips = true;
        } else if (relationship.shouldWriteJoinTable) {
            hasJoinRelationShips = true;
        }

        // at least one relationship must update fields
        if (!relationshipsToRecreateForeignKeysOnly.includes(relationship)) {
            hasRelationshipWithFieldUpdates = true;
        }
    }
    /* ======== Start removed relationships should be written ======== */
    if (hasRelationShips || hasJoinRelationShips) {
     _%>

    <!--
        Dropped relationships to the entity <%= entity.entityClass %>.
    -->
    <changeSet id="<%= changelogDate %>-1-drop-relationships" author="jhipster">
        <%_
        /* ======== Start hasRelationShips ======== */
        if (hasRelationShips) {
            /* ======== Start dropForeignKeyConstraint ======== */
            for (relationship of removedRelationships) {
                if (relationship.shouldWriteRelationship) {
        _%>
        <dropForeignKeyConstraint baseTableName="<%= entity.entityTableName %>" constraintName="<%= this.getFKConstraintName(entity.entityTableName, relationship.relationshipName, prodDatabaseType) %>"/>
        <%_     }
            }

            if (hasRelationshipWithFieldUpdates) {
            /* ======== End dropForeignKeyConstraint ======== */ _%>
        <dropColumn tableName="<%= entity.entityTableName %>">
        <%_
            /* ======== Start drop relationship columns ======== */
            for (relationship of removedRelationships) {
                if (relationship.shouldWriteRelationship && !relationshipsToRecreateForeignKeysOnly.includes(relationship)) {
                    for (const otherEntityPkField of relationship.otherEntity.primaryKey.fields) { _%>
            <column name="<%= relationship.columnName %>_<%= otherEntityPkField.columnName %>"/>
                    <%_ } _%>
        <%_     }
            }
            /* ======== End drop relationship column ======== */ _%>
        </dropColumn>
        <%_
            }
        }
        /* ======== End hasRelationShips ======== */ _%>
        <%_
        /* ======== Start for joinTable ======== */
        for (relationship of removedRelationships) {
            if (relationship.shouldWriteJoinTable) { _%>
        <dropTable cascadeConstraints="true" tableName="<%= relationship.joinTable.name %>"/>
            <%_ }
        }
        /* ======== End for joinTable ======== */ _%>
    </changeSet>
    <%_
    }
    /* ======== End removed relationships should be written ======== */
}
/* ======== End removed relationships exists ======== */ _%>

    <!-- jhipster-needle-liquibase-add-changeset - JHipster will add changesets here -->

</databaseChangeLog>
