<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
    xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd
                        http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">

    <!--
        Altered the entity DashboardComponentDetail.
        #1 Add sort column
    -->
    <changeSet id="20250228164500-1" author="omg">
    	<!-- Step 1: Add column -->
    	<addColumn tableName="dashboard_component_detail">
	        <column name="idx_order" type="int" />
	    </addColumn>
    </changeSet>
    
    <!-- Step 2: Populate column with sequential numbers -->
	<changeSet id="20250228164500-2" author="omg">
	    <sql>
	        SET @row_number = 0;
	        UPDATE dashboard_component_detail
	        JOIN (SELECT id FROM dashboard_component_detail ORDER BY id) sorted
	        ON dashboard_component_detail.id = sorted.id
	        SET dashboard_component_detail.idx_order = (@row_number := @row_number + 1);
	    </sql>
	</changeSet>

    <!-- Step 3: Make the column non-nullable -->
    <changeSet id="20250228164500-3" author="omg">
	    <addNotNullConstraint tableName="dashboard_component_detail" columnName="idx_order" columnDataType="int"/>
	</changeSet>
</databaseChangeLog>
