// <auto-generated />
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace AliasServerDb.Migrations
{
    /// <summary>
    /// Migration to set default revision numbers for vaults.
    /// </summary>
    public partial class SetDefaultRevisionNumber : Migration
    {
        /// <summary>
        /// Applies the migration, setting incremental revision numbers for each user's vaults.
        /// </summary>
        /// <param name="migrationBuilder">The migration builder.</param>
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(@"
                UPDATE Vaults
                SET RevisionNumber = (
                    SELECT COUNT(*)
                    FROM Vaults AS v2
                    WHERE v2.UserId = Vaults.UserId
                        AND (v2.UpdatedAt < Vaults.UpdatedAt
                            OR (v2.UpdatedAt = Vaults.UpdatedAt AND v2.Id <= Vaults.Id))
                ) - 1;
            ");
        }

        /// <summary>
        /// Reverts the migration by setting all RevisionNumber values to 0.
        /// </summary>
        /// <param name="migrationBuilder">The migration builder.</param>
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql("UPDATE Vaults SET RevisionNumber = 0;");
        }
    }
}
