using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace TakeoutSaaS.Infrastructure.Migrations.IdentityDb
{
    /// <inheritdoc />
    public partial class AddIdentityUserManagementFields : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "Email",
                table: "identity_users",
                type: "character varying(128)",
                maxLength: 128,
                nullable: true,
                comment: "邮箱（租户内唯一）。");

            migrationBuilder.AddColumn<int>(
                name: "FailedLoginCount",
                table: "identity_users",
                type: "integer",
                nullable: false,
                defaultValue: 0,
                comment: "登录失败次数。");

            migrationBuilder.AddColumn<DateTime>(
                name: "LastLoginAt",
                table: "identity_users",
                type: "timestamp with time zone",
                nullable: true,
                comment: "最近登录时间（UTC）。");

            migrationBuilder.AddColumn<DateTime>(
                name: "LockedUntil",
                table: "identity_users",
                type: "timestamp with time zone",
                nullable: true,
                comment: "锁定截止时间（UTC）。");

            migrationBuilder.AddColumn<bool>(
                name: "MustChangePassword",
                table: "identity_users",
                type: "boolean",
                nullable: false,
                defaultValue: false,
                comment: "是否强制修改密码。");

            migrationBuilder.AddColumn<string>(
                name: "Phone",
                table: "identity_users",
                type: "character varying(32)",
                maxLength: 32,
                nullable: true,
                comment: "手机号（租户内唯一）。");

            migrationBuilder.AddColumn<byte[]>(
                name: "RowVersion",
                table: "identity_users",
                type: "bytea",
                rowVersion: true,
                nullable: false,
                defaultValue: new byte[0],
                comment: "并发控制字段。");

            migrationBuilder.AddColumn<int>(
                name: "Status",
                table: "identity_users",
                type: "integer",
                nullable: false,
                defaultValue: 1,
                comment: "账号状态。");

            // 1. 修复历史用户默认状态为启用
            migrationBuilder.Sql(
                """
                UPDATE identity_users
                SET "Status" = 1
                WHERE "Status" = 0;
                """);

            // 2. 创建 RowVersion 触发器，确保并发字段自动更新
            migrationBuilder.Sql(
                """
                CREATE OR REPLACE FUNCTION public.set_identity_user_row_version()
                RETURNS trigger AS $$
                BEGIN
                    NEW."RowVersion" = decode(md5(random()::text || clock_timestamp()::text), 'hex');
                    RETURN NEW;
                END;
                $$ LANGUAGE plpgsql;
                """);

            migrationBuilder.Sql(
                """
                DROP TRIGGER IF EXISTS trg_identity_users_row_version ON identity_users;
                CREATE TRIGGER trg_identity_users_row_version
                BEFORE INSERT OR UPDATE ON identity_users
                FOR EACH ROW EXECUTE FUNCTION public.set_identity_user_row_version();
                """);

            // 3. 回填已有数据的 RowVersion
            migrationBuilder.Sql(
                """
                UPDATE identity_users
                SET "RowVersion" = decode(md5(random()::text || clock_timestamp()::text), 'hex')
                WHERE "RowVersion" IS NULL OR octet_length("RowVersion") = 0;
                """);

            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");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(
                """
                DROP TRIGGER IF EXISTS trg_identity_users_row_version ON identity_users;
                DROP FUNCTION IF EXISTS public.set_identity_user_row_version();
                """);

            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: "Email",
                table: "identity_users");

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

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

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

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

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

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

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