using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

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

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

            migrationBuilder.CreateIndex(
                name: "idx_tasks_list_sort",
                table: "tasks",
                columns: new[] { "list_id", "sort_order" });
        }

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

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