using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

#nullable disable

namespace TakeoutSaaS.Infrastructure.Migrations.IdentityDb
{
    /// <inheritdoc />
    public partial class PortalizeIdentityRbac : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropIndex(
                name: "IX_user_roles_TenantId",
                table: "user_roles");

            migrationBuilder.DropIndex(
                name: "IX_user_roles_TenantId_UserId_RoleId",
                table: "user_roles");

            migrationBuilder.DropIndex(
                name: "IX_roles_TenantId",
                table: "roles");

            migrationBuilder.DropIndex(
                name: "IX_roles_TenantId_Code",
                table: "roles");

            migrationBuilder.DropIndex(
                name: "IX_role_permissions_TenantId",
                table: "role_permissions");

            migrationBuilder.DropIndex(
                name: "IX_role_permissions_TenantId_RoleId_PermissionId",
                table: "role_permissions");

            migrationBuilder.DropIndex(
                name: "IX_permissions_TenantId",
                table: "permissions");

            migrationBuilder.DropIndex(
                name: "IX_permissions_TenantId_Code",
                table: "permissions");

            migrationBuilder.DropIndex(
                name: "IX_permissions_TenantId_ParentId_SortOrder",
                table: "permissions");

            migrationBuilder.DropIndex(
                name: "IX_menu_definitions_TenantId_ParentId_SortOrder",
                table: "menu_definitions");

            migrationBuilder.DropIndex(
                name: "IX_identity_users_TenantId",
                table: "identity_users");

            migrationBuilder.DropIndex(
                name: "IX_identity_users_TenantId_Account",
                table: "identity_users");

            migrationBuilder.DropIndex(
                name: "IX_identity_users_TenantId_Email",
                table: "identity_users");

            migrationBuilder.DropIndex(
                name: "IX_identity_users_TenantId_Phone",
                table: "identity_users");

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

            migrationBuilder.DropColumn(
                name: "TenantId",
                table: "menu_definitions");

            migrationBuilder.AlterTable(
                name: "menu_definitions",
                comment: "后台菜单定义（按 Portal 区分 Admin/Tenant 两套菜单树）。",
                oldComment: "管理端菜单定义。");

            migrationBuilder.AlterTable(
                name: "identity_users",
                comment: "后台账户实体（按 Portal 区分平台管理员与租户后台账号）。",
                oldComment: "管理后台账户实体（平台管理员、租户管理员或商户员工）。");

            migrationBuilder.AlterColumn<long>(
                name: "TenantId",
                table: "user_roles",
                type: "bigint",
                nullable: true,
                comment: "所属租户 ID（Portal=Tenant 时必填；Portal=Admin 时必须为空）。",
                oldClrType: typeof(long),
                oldType: "bigint",
                oldComment: "所属租户 ID。");

            migrationBuilder.AddColumn<int>(
                name: "Portal",
                table: "user_roles",
                type: "integer",
                nullable: false,
                defaultValue: 0,
                comment: "关系所属 Portal。");

            migrationBuilder.AlterColumn<long>(
                name: "TenantId",
                table: "roles",
                type: "bigint",
                nullable: true,
                comment: "所属租户 ID（Portal=Tenant 时必填；Portal=Admin 时必须为空）。",
                oldClrType: typeof(long),
                oldType: "bigint",
                oldComment: "所属租户 ID。");

            migrationBuilder.AddColumn<int>(
                name: "Portal",
                table: "roles",
                type: "integer",
                nullable: false,
                defaultValue: 0,
                comment: "角色所属 Portal。");

            migrationBuilder.AlterColumn<long>(
                name: "TenantId",
                table: "role_permissions",
                type: "bigint",
                nullable: true,
                comment: "所属租户 ID（Portal=Tenant 时必填；Portal=Admin 时必须为空）。",
                oldClrType: typeof(long),
                oldType: "bigint",
                oldComment: "所属租户 ID。");

            migrationBuilder.AddColumn<int>(
                name: "Portal",
                table: "role_permissions",
                type: "integer",
                nullable: false,
                defaultValue: 0,
                comment: "关系所属 Portal。");

            migrationBuilder.AlterColumn<string>(
                name: "Code",
                table: "permissions",
                type: "character varying(128)",
                maxLength: 128,
                nullable: false,
                comment: "权限编码（全局唯一）。",
                oldClrType: typeof(string),
                oldType: "character varying(128)",
                oldMaxLength: 128,
                oldComment: "权限编码（租户内唯一）。");

            migrationBuilder.AddColumn<int>(
                name: "Portal",
                table: "permissions",
                type: "integer",
                nullable: false,
                defaultValue: 0,
                comment: "权限所属 Portal。");

            migrationBuilder.AddColumn<int>(
                name: "Portal",
                table: "menu_definitions",
                type: "integer",
                nullable: false,
                defaultValue: 0,
                comment: "菜单所属 Portal。");

            migrationBuilder.AlterColumn<long>(
                name: "TenantId",
                table: "identity_users",
                type: "bigint",
                nullable: true,
                comment: "所属租户 ID（Portal=Tenant 时必填；Portal=Admin 时必须为空）。",
                oldClrType: typeof(long),
                oldType: "bigint",
                oldComment: "所属租户 ID。");

            migrationBuilder.AddColumn<int>(
                name: "Portal",
                table: "identity_users",
                type: "integer",
                nullable: false,
                defaultValue: 0,
                comment: "账号所属 Portal。");

            migrationBuilder.CreateTable(
                name: "InboxState",
                columns: table => new
                {
                    Id = table.Column<long>(type: "bigint", nullable: false)
                        .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
                    MessageId = table.Column<Guid>(type: "uuid", nullable: false),
                    ConsumerId = table.Column<Guid>(type: "uuid", nullable: false),
                    LockId = table.Column<Guid>(type: "uuid", nullable: false),
                    RowVersion = table.Column<byte[]>(type: "bytea", nullable: true),
                    Received = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
                    ReceiveCount = table.Column<int>(type: "integer", nullable: false),
                    ExpirationTime = table.Column<DateTime>(type: "timestamp with time zone", nullable: true),
                    Consumed = table.Column<DateTime>(type: "timestamp with time zone", nullable: true),
                    Delivered = table.Column<DateTime>(type: "timestamp with time zone", nullable: true),
                    LastSequenceNumber = table.Column<long>(type: "bigint", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_InboxState", x => x.Id);
                    table.UniqueConstraint("AK_InboxState_MessageId_ConsumerId", x => new { x.MessageId, x.ConsumerId });
                });

            migrationBuilder.Sql(
                """
                -- 1. 角色 Portal 回填：除 PlatformAdmin 外均视为租户端角色
                UPDATE public.roles SET "Portal" = 1;
                UPDATE public.roles
                SET "Portal" = 0,
                    "TenantId" = NULL
                WHERE "Code" = 'PlatformAdmin';

                -- 2. 用户 Portal 回填：拥有 PlatformAdmin 角色的账号视为平台管理员
                UPDATE public.identity_users SET "Portal" = 1;
                UPDATE public.identity_users u
                SET "Portal" = 0,
                    "TenantId" = NULL
                WHERE EXISTS (
                    SELECT 1
                    FROM public.user_roles ur
                    JOIN public.roles r ON r."Id" = ur."RoleId"
                    WHERE ur."UserId" = u."Id"
                      AND r."Portal" = 0
                );

                -- 3. 关系表 Portal 回填：按关联角色 Portal 写入，并对平台侧关系清空 TenantId
                UPDATE public.user_roles ur
                SET "Portal" = r."Portal"
                FROM public.roles r
                WHERE r."Id" = ur."RoleId";

                UPDATE public.user_roles
                SET "TenantId" = NULL
                WHERE "Portal" = 0;

                UPDATE public.role_permissions rp
                SET "Portal" = r."Portal"
                FROM public.roles r
                WHERE r."Id" = rp."RoleId";

                UPDATE public.role_permissions
                SET "TenantId" = NULL
                WHERE "Portal" = 0;

                -- 4. 菜单与权限默认归属 Admin Portal（Tenant Portal 后续由 TenantApi 单独初始化）
                UPDATE public.menu_definitions SET "Portal" = 0;
                UPDATE public.permissions SET "Portal" = 0;
                """);

            migrationBuilder.CreateIndex(
                name: "IX_user_roles_TenantId",
                table: "user_roles",
                column: "TenantId",
                filter: "\"Portal\" = 1");

            migrationBuilder.CreateIndex(
                name: "IX_user_roles_TenantId_UserId_RoleId",
                table: "user_roles",
                columns: new[] { "TenantId", "UserId", "RoleId" },
                unique: true,
                filter: "\"Portal\" = 1");

            migrationBuilder.CreateIndex(
                name: "IX_user_roles_UserId_RoleId",
                table: "user_roles",
                columns: new[] { "UserId", "RoleId" },
                unique: true,
                filter: "\"Portal\" = 0");

            migrationBuilder.AddCheckConstraint(
                name: "CK_user_roles_Portal_Tenant",
                table: "user_roles",
                sql: "(\"Portal\" = 0 AND \"TenantId\" IS NULL) OR (\"Portal\" = 1 AND \"TenantId\" IS NOT NULL)");

            migrationBuilder.CreateIndex(
                name: "IX_roles_Code",
                table: "roles",
                column: "Code",
                unique: true,
                filter: "\"Portal\" = 0");

            migrationBuilder.CreateIndex(
                name: "IX_roles_TenantId",
                table: "roles",
                column: "TenantId",
                filter: "\"Portal\" = 1");

            migrationBuilder.CreateIndex(
                name: "IX_roles_TenantId_Code",
                table: "roles",
                columns: new[] { "TenantId", "Code" },
                unique: true,
                filter: "\"Portal\" = 1");

            migrationBuilder.AddCheckConstraint(
                name: "CK_roles_Portal_Tenant",
                table: "roles",
                sql: "(\"Portal\" = 0 AND \"TenantId\" IS NULL) OR (\"Portal\" = 1 AND \"TenantId\" IS NOT NULL)");

            migrationBuilder.CreateIndex(
                name: "IX_role_permissions_RoleId_PermissionId",
                table: "role_permissions",
                columns: new[] { "RoleId", "PermissionId" },
                unique: true,
                filter: "\"Portal\" = 0");

            migrationBuilder.CreateIndex(
                name: "IX_role_permissions_TenantId",
                table: "role_permissions",
                column: "TenantId",
                filter: "\"Portal\" = 1");

            migrationBuilder.CreateIndex(
                name: "IX_role_permissions_TenantId_RoleId_PermissionId",
                table: "role_permissions",
                columns: new[] { "TenantId", "RoleId", "PermissionId" },
                unique: true,
                filter: "\"Portal\" = 1");

            migrationBuilder.AddCheckConstraint(
                name: "CK_role_permissions_Portal_Tenant",
                table: "role_permissions",
                sql: "(\"Portal\" = 0 AND \"TenantId\" IS NULL) OR (\"Portal\" = 1 AND \"TenantId\" IS NOT NULL)");

            migrationBuilder.CreateIndex(
                name: "IX_permissions_Code",
                table: "permissions",
                column: "Code",
                unique: true);

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

            migrationBuilder.CreateIndex(
                name: "IX_menu_definitions_Portal_ParentId_SortOrder",
                table: "menu_definitions",
                columns: new[] { "Portal", "ParentId", "SortOrder" });

            migrationBuilder.CreateIndex(
                name: "IX_identity_users_Account",
                table: "identity_users",
                column: "Account",
                unique: true,
                filter: "\"Portal\" = 0");

            migrationBuilder.CreateIndex(
                name: "IX_identity_users_Email",
                table: "identity_users",
                column: "Email",
                unique: true,
                filter: "\"Portal\" = 0 AND \"Email\" IS NOT NULL");

            migrationBuilder.CreateIndex(
                name: "IX_identity_users_Phone",
                table: "identity_users",
                column: "Phone",
                unique: true,
                filter: "\"Portal\" = 0 AND \"Phone\" IS NOT NULL");

            migrationBuilder.CreateIndex(
                name: "IX_identity_users_TenantId",
                table: "identity_users",
                column: "TenantId",
                filter: "\"Portal\" = 1");

            migrationBuilder.CreateIndex(
                name: "IX_identity_users_TenantId_Account",
                table: "identity_users",
                columns: new[] { "TenantId", "Account" },
                unique: true,
                filter: "\"Portal\" = 1");

            migrationBuilder.CreateIndex(
                name: "IX_identity_users_TenantId_Email",
                table: "identity_users",
                columns: new[] { "TenantId", "Email" },
                unique: true,
                filter: "\"Portal\" = 1 AND \"Email\" IS NOT NULL");

            migrationBuilder.CreateIndex(
                name: "IX_identity_users_TenantId_Phone",
                table: "identity_users",
                columns: new[] { "TenantId", "Phone" },
                unique: true,
                filter: "\"Portal\" = 1 AND \"Phone\" IS NOT NULL");

            migrationBuilder.AddCheckConstraint(
                name: "CK_identity_users_Portal_Tenant",
                table: "identity_users",
                sql: "(\"Portal\" = 0 AND \"TenantId\" IS NULL) OR (\"Portal\" = 1 AND \"TenantId\" IS NOT NULL)");

            migrationBuilder.AddForeignKey(
                name: "FK_OutboxMessage_InboxState_InboxMessageId_InboxConsumerId",
                table: "OutboxMessage",
                columns: new[] { "InboxMessageId", "InboxConsumerId" },
                principalTable: "InboxState",
                principalColumns: new[] { "MessageId", "ConsumerId" });

            migrationBuilder.AddForeignKey(
                name: "FK_OutboxMessage_OutboxState_OutboxId",
                table: "OutboxMessage",
                column: "OutboxId",
                principalTable: "OutboxState",
                principalColumn: "OutboxId");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK_OutboxMessage_InboxState_InboxMessageId_InboxConsumerId",
                table: "OutboxMessage");

            migrationBuilder.DropForeignKey(
                name: "FK_OutboxMessage_OutboxState_OutboxId",
                table: "OutboxMessage");

            migrationBuilder.DropTable(
                name: "InboxState");

            migrationBuilder.DropIndex(
                name: "IX_user_roles_TenantId",
                table: "user_roles");

            migrationBuilder.DropIndex(
                name: "IX_user_roles_TenantId_UserId_RoleId",
                table: "user_roles");

            migrationBuilder.DropIndex(
                name: "IX_user_roles_UserId_RoleId",
                table: "user_roles");

            migrationBuilder.DropCheckConstraint(
                name: "CK_user_roles_Portal_Tenant",
                table: "user_roles");

            migrationBuilder.DropIndex(
                name: "IX_roles_Code",
                table: "roles");

            migrationBuilder.DropIndex(
                name: "IX_roles_TenantId",
                table: "roles");

            migrationBuilder.DropIndex(
                name: "IX_roles_TenantId_Code",
                table: "roles");

            migrationBuilder.DropCheckConstraint(
                name: "CK_roles_Portal_Tenant",
                table: "roles");

            migrationBuilder.DropIndex(
                name: "IX_role_permissions_RoleId_PermissionId",
                table: "role_permissions");

            migrationBuilder.DropIndex(
                name: "IX_role_permissions_TenantId",
                table: "role_permissions");

            migrationBuilder.DropIndex(
                name: "IX_role_permissions_TenantId_RoleId_PermissionId",
                table: "role_permissions");

            migrationBuilder.DropCheckConstraint(
                name: "CK_role_permissions_Portal_Tenant",
                table: "role_permissions");

            migrationBuilder.DropIndex(
                name: "IX_permissions_Code",
                table: "permissions");

            migrationBuilder.DropIndex(
                name: "IX_permissions_Portal_ParentId_SortOrder",
                table: "permissions");

            migrationBuilder.DropIndex(
                name: "IX_menu_definitions_Portal_ParentId_SortOrder",
                table: "menu_definitions");

            migrationBuilder.DropIndex(
                name: "IX_identity_users_Account",
                table: "identity_users");

            migrationBuilder.DropIndex(
                name: "IX_identity_users_Email",
                table: "identity_users");

            migrationBuilder.DropIndex(
                name: "IX_identity_users_Phone",
                table: "identity_users");

            migrationBuilder.DropIndex(
                name: "IX_identity_users_TenantId",
                table: "identity_users");

            migrationBuilder.DropIndex(
                name: "IX_identity_users_TenantId_Account",
                table: "identity_users");

            migrationBuilder.DropIndex(
                name: "IX_identity_users_TenantId_Email",
                table: "identity_users");

            migrationBuilder.DropIndex(
                name: "IX_identity_users_TenantId_Phone",
                table: "identity_users");

            migrationBuilder.DropCheckConstraint(
                name: "CK_identity_users_Portal_Tenant",
                table: "identity_users");

            migrationBuilder.DropColumn(
                name: "Portal",
                table: "user_roles");

            migrationBuilder.DropColumn(
                name: "Portal",
                table: "roles");

            migrationBuilder.DropColumn(
                name: "Portal",
                table: "role_permissions");

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

            migrationBuilder.DropColumn(
                name: "Portal",
                table: "menu_definitions");

            migrationBuilder.DropColumn(
                name: "Portal",
                table: "identity_users");

            migrationBuilder.AlterTable(
                name: "menu_definitions",
                comment: "管理端菜单定义。",
                oldComment: "后台菜单定义（按 Portal 区分 Admin/Tenant 两套菜单树）。");

            migrationBuilder.AlterTable(
                name: "identity_users",
                comment: "管理后台账户实体（平台管理员、租户管理员或商户员工）。",
                oldComment: "后台账户实体（按 Portal 区分平台管理员与租户后台账号）。");

            migrationBuilder.AlterColumn<long>(
                name: "TenantId",
                table: "user_roles",
                type: "bigint",
                nullable: false,
                defaultValue: 0L,
                comment: "所属租户 ID。",
                oldClrType: typeof(long),
                oldType: "bigint",
                oldNullable: true,
                oldComment: "所属租户 ID（Portal=Tenant 时必填；Portal=Admin 时必须为空）。");

            migrationBuilder.AlterColumn<long>(
                name: "TenantId",
                table: "roles",
                type: "bigint",
                nullable: false,
                defaultValue: 0L,
                comment: "所属租户 ID。",
                oldClrType: typeof(long),
                oldType: "bigint",
                oldNullable: true,
                oldComment: "所属租户 ID（Portal=Tenant 时必填；Portal=Admin 时必须为空）。");

            migrationBuilder.AlterColumn<long>(
                name: "TenantId",
                table: "role_permissions",
                type: "bigint",
                nullable: false,
                defaultValue: 0L,
                comment: "所属租户 ID。",
                oldClrType: typeof(long),
                oldType: "bigint",
                oldNullable: true,
                oldComment: "所属租户 ID（Portal=Tenant 时必填；Portal=Admin 时必须为空）。");

            migrationBuilder.AlterColumn<string>(
                name: "Code",
                table: "permissions",
                type: "character varying(128)",
                maxLength: 128,
                nullable: false,
                comment: "权限编码（租户内唯一）。",
                oldClrType: typeof(string),
                oldType: "character varying(128)",
                oldMaxLength: 128,
                oldComment: "权限编码（全局唯一）。");

            migrationBuilder.AddColumn<long>(
                name: "TenantId",
                table: "permissions",
                type: "bigint",
                nullable: false,
                defaultValue: 0L,
                comment: "所属租户 ID。");

            migrationBuilder.AddColumn<long>(
                name: "TenantId",
                table: "menu_definitions",
                type: "bigint",
                nullable: false,
                defaultValue: 0L,
                comment: "所属租户 ID。");

            migrationBuilder.AlterColumn<long>(
                name: "TenantId",
                table: "identity_users",
                type: "bigint",
                nullable: false,
                defaultValue: 0L,
                comment: "所属租户 ID。",
                oldClrType: typeof(long),
                oldType: "bigint",
                oldNullable: true,
                oldComment: "所属租户 ID（Portal=Tenant 时必填；Portal=Admin 时必须为空）。");

            migrationBuilder.CreateIndex(
                name: "IX_user_roles_TenantId",
                table: "user_roles",
                column: "TenantId");

            migrationBuilder.CreateIndex(
                name: "IX_user_roles_TenantId_UserId_RoleId",
                table: "user_roles",
                columns: new[] { "TenantId", "UserId", "RoleId" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_roles_TenantId",
                table: "roles",
                column: "TenantId");

            migrationBuilder.CreateIndex(
                name: "IX_roles_TenantId_Code",
                table: "roles",
                columns: new[] { "TenantId", "Code" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_role_permissions_TenantId",
                table: "role_permissions",
                column: "TenantId");

            migrationBuilder.CreateIndex(
                name: "IX_role_permissions_TenantId_RoleId_PermissionId",
                table: "role_permissions",
                columns: new[] { "TenantId", "RoleId", "PermissionId" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_permissions_TenantId",
                table: "permissions",
                column: "TenantId");

            migrationBuilder.CreateIndex(
                name: "IX_permissions_TenantId_Code",
                table: "permissions",
                columns: new[] { "TenantId", "Code" },
                unique: true);

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

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

            migrationBuilder.CreateIndex(
                name: "IX_identity_users_TenantId",
                table: "identity_users",
                column: "TenantId");

            migrationBuilder.CreateIndex(
                name: "IX_identity_users_TenantId_Account",
                table: "identity_users",
                columns: new[] { "TenantId", "Account" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_identity_users_TenantId_Email",
                table: "identity_users",
                columns: new[] { "TenantId", "Email" },
                unique: true,
                filter: "\"Email\" IS NOT NULL");

            migrationBuilder.CreateIndex(
                name: "IX_identity_users_TenantId_Phone",
                table: "identity_users",
                columns: new[] { "TenantId", "Phone" },
                unique: true,
                filter: "\"Phone\" IS NOT NULL");
        }
    }
}
