using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace ClaudeDo.Data.Migrations
{
    /// <inheritdoc />
    public partial class NormalizeListIdFormat : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            // SQLite: PRAGMA foreign_keys must run outside a transaction.
            migrationBuilder.Sql("PRAGMA foreign_keys = OFF;", suppressTransaction: true);

            // Normalize tasks.list_id: 32-char compact hex → 36-char dashed UUID
            migrationBuilder.Sql("""
                UPDATE tasks
                SET list_id = substr(list_id,1,8)||'-'||substr(list_id,9,4)||'-'||substr(list_id,13,4)||'-'||substr(list_id,17,4)||'-'||substr(list_id,21,12)
                WHERE length(list_id) = 32;
                """);

            // Normalize list_config.list_id (also the PK of that table)
            migrationBuilder.Sql("""
                UPDATE list_config
                SET list_id = substr(list_id,1,8)||'-'||substr(list_id,9,4)||'-'||substr(list_id,13,4)||'-'||substr(list_id,17,4)||'-'||substr(list_id,21,12)
                WHERE length(list_id) = 32;
                """);

            // Normalize lists.id (PK — must come last)
            migrationBuilder.Sql("""
                UPDATE lists
                SET id = substr(id,1,8)||'-'||substr(id,9,4)||'-'||substr(id,13,4)||'-'||substr(id,17,4)||'-'||substr(id,21,12)
                WHERE length(id) = 32;
                """);

            migrationBuilder.Sql("PRAGMA foreign_keys = ON;", suppressTransaction: true);
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql("PRAGMA foreign_keys = OFF;", suppressTransaction: true);

            migrationBuilder.Sql("UPDATE tasks SET list_id = replace(list_id,'-','') WHERE length(list_id) = 36;");
            migrationBuilder.Sql("UPDATE list_config SET list_id = replace(list_id,'-','') WHERE length(list_id) = 36;");
            migrationBuilder.Sql("UPDATE lists SET id = replace(id,'-','') WHERE length(id) = 36;");

            migrationBuilder.Sql("PRAGMA foreign_keys = ON;", suppressTransaction: true);
        }
    }
}
