using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace ClaudeDo.Data.Migrations
{
    /// <inheritdoc />
    public partial class AddListSortOrder : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<int>(
                name: "sort_order",
                table: "lists",
                type: "INTEGER",
                nullable: false,
                defaultValue: 0);

            // Backfill existing rows with a dense order (0..N-1) by creation time
            // so today's sidebar order is preserved after the migration.
            migrationBuilder.Sql("""
                WITH ordered AS (
                    SELECT id, (row_number() OVER (ORDER BY created_at) - 1) AS rn
                    FROM lists
                )
                UPDATE lists SET sort_order = (SELECT rn FROM ordered WHERE ordered.id = lists.id);
                """);

            migrationBuilder.CreateIndex(
                name: "idx_lists_sort",
                table: "lists",
                column: "sort_order");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropIndex(
                name: "idx_lists_sort",
                table: "lists");

            migrationBuilder.DropColumn(
                name: "sort_order",
                table: "lists");
        }
    }
}
