using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace TakeoutSaaS.Infrastructure.Migrations.IdentityDb
{
    /// <inheritdoc />
    public partial class AddPermissionHierarchyFields : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<long>(
                name: "ParentId",
                table: "permissions",
                type: "bigint",
                nullable: false,
                defaultValue: 0L,
                comment: "父级权限 ID，根节点为 0。");

            migrationBuilder.AddColumn<int>(
                name: "SortOrder",
                table: "permissions",
                type: "integer",
                nullable: false,
                defaultValue: 0,
                comment: "排序值，值越小越靠前。");

            migrationBuilder.AddColumn<string>(
                name: "Type",
                table: "permissions",
                type: "character varying(16)",
                maxLength: 16,
                nullable: false,
                defaultValue: "leaf",
                comment: "权限类型（group/leaf）。");

            migrationBuilder.CreateIndex(
                name: "IX_permissions_TenantId_ParentId_SortOrder",
                table: "permissions",
                columns: new[] { "TenantId", "ParentId", "SortOrder" });

            migrationBuilder.Sql(
                "UPDATE \"permissions\" SET \"Type\" = 'leaf' WHERE \"Type\" IS NULL OR \"Type\" = '';");
        }

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

            migrationBuilder.DropColumn(
                name: "ParentId",
                table: "permissions");

            migrationBuilder.DropColumn(
                name: "SortOrder",
                table: "permissions");

            migrationBuilder.DropColumn(
                name: "Type",
                table: "permissions");
        }
    }
}
