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

#nullable disable

namespace TakeoutSaaS.Infrastructure.Migrations.DictionaryDb
{
    /// <inheritdoc />
    public partial class UpdateDictionarySchema : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropIndex(
                name: "IX_dictionary_items_GroupId_Key",
                table: "dictionary_items");

            migrationBuilder.DropIndex(
                name: "IX_dictionary_groups_TenantId_Code",
                table: "dictionary_groups");

            // 使用原生 SQL 进行类型转换，确保现有数据被正确转换为 JSONB
            migrationBuilder.Sql(
                """
                ALTER TABLE dictionary_items
                ALTER COLUMN "Value" TYPE jsonb
                USING to_jsonb("Value"::text);

                COMMENT ON COLUMN dictionary_items."Value" IS '字典项值。';
                """);

            migrationBuilder.AlterColumn<string>(
                name: "Key",
                table: "dictionary_items",
                type: "character varying(128)",
                maxLength: 128,
                nullable: false,
                comment: "字典项键。",
                oldClrType: typeof(string),
                oldType: "character varying(64)",
                oldMaxLength: 64,
                oldComment: "字典项键。");

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

            migrationBuilder.AlterColumn<string>(
                name: "Code",
                table: "dictionary_groups",
                type: "character varying(64)",
                maxLength: 64,
                nullable: false,
                oldClrType: typeof(string),
                oldType: "character varying(64)",
                oldMaxLength: 64,
                oldComment: "分组编码（唯一）。");

            migrationBuilder.AddColumn<bool>(
                name: "AllowOverride",
                table: "dictionary_groups",
                type: "boolean",
                nullable: false,
                defaultValue: false,
                comment: "是否允许租户覆盖。");

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

            migrationBuilder.CreateTable(
                name: "dictionary_import_logs",
                columns: table => new
                {
                    Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
                        .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
                    OperatorId = table.Column<long>(type: "bigint", nullable: false, comment: "操作人用户标识。"),
                    DictionaryGroupCode = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false, comment: "字典分组编码。"),
                    FileName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false, comment: "导入文件名。"),
                    FileSize = table.Column<long>(type: "bigint", nullable: false, comment: "文件大小（字节）。"),
                    Format = table.Column<string>(type: "character varying(16)", maxLength: 16, nullable: false, comment: "文件格式（CSV/JSON）。"),
                    ConflictMode = table.Column<int>(type: "integer", nullable: false, comment: "冲突处理模式。"),
                    SuccessCount = table.Column<int>(type: "integer", nullable: false, comment: "成功导入数量。"),
                    SkipCount = table.Column<int>(type: "integer", nullable: false, comment: "跳过数量。"),
                    ErrorDetails = table.Column<string>(type: "jsonb", nullable: true, comment: "错误明细（JSON）。"),
                    ProcessedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "处理时间（UTC）。"),
                    Duration = table.Column<TimeSpan>(type: "interval", nullable: false, comment: "处理耗时。"),
                    CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间（UTC）。"),
                    UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间（UTC），从未更新时为 null。"),
                    DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间（UTC），未删除时为 null。"),
                    CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识，匿名或系统操作时为 null。"),
                    UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识，匿名或系统操作时为 null。"),
                    DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识（软删除），未删除时为 null。"),
                    TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_dictionary_import_logs", x => x.Id);
                },
                comment: "字典导入审计日志。");

            migrationBuilder.CreateTable(
                name: "tenant_dictionary_overrides",
                columns: table => new
                {
                    TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。"),
                    SystemDictionaryGroupId = table.Column<long>(type: "bigint", nullable: false, comment: "系统字典分组 ID。"),
                    OverrideEnabled = table.Column<bool>(type: "boolean", nullable: false, defaultValue: false, comment: "是否启用覆盖。"),
                    HiddenSystemItemIds = table.Column<long[]>(type: "bigint[]", nullable: false, comment: "隐藏的系统字典项 ID 列表。"),
                    CustomSortOrder = table.Column<string>(type: "jsonb", nullable: false, comment: "自定义排序映射（JSON）。"),
                    CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间（UTC）。"),
                    UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近更新时间（UTC）。"),
                    DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "删除时间（UTC）。"),
                    CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识。"),
                    UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识。"),
                    DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识。")
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_tenant_dictionary_overrides", x => new { x.TenantId, x.SystemDictionaryGroupId });
                },
                comment: "租户字典覆盖配置。");

            migrationBuilder.CreateIndex(
                name: "IX_dictionary_items_GroupId_IsEnabled_SortOrder",
                table: "dictionary_items",
                columns: new[] { "GroupId", "IsEnabled", "SortOrder" });

            migrationBuilder.CreateIndex(
                name: "IX_dictionary_items_TenantId_GroupId_Key",
                table: "dictionary_items",
                columns: new[] { "TenantId", "GroupId", "Key" },
                unique: true,
                filter: "\"DeletedAt\" IS NULL");

            migrationBuilder.CreateIndex(
                name: "IX_dictionary_groups_TenantId_Code",
                table: "dictionary_groups",
                columns: new[] { "TenantId", "Code" },
                unique: true,
                filter: "\"DeletedAt\" IS NULL");

            migrationBuilder.CreateIndex(
                name: "IX_dictionary_groups_TenantId_Scope_IsEnabled",
                table: "dictionary_groups",
                columns: new[] { "TenantId", "Scope", "IsEnabled" });

            migrationBuilder.CreateIndex(
                name: "IX_dictionary_import_logs_TenantId_ProcessedAt",
                table: "dictionary_import_logs",
                columns: new[] { "TenantId", "ProcessedAt" });

            migrationBuilder.CreateIndex(
                name: "IX_tenant_dictionary_overrides_HiddenSystemItemIds",
                table: "tenant_dictionary_overrides",
                column: "HiddenSystemItemIds")
                .Annotation("Npgsql:IndexMethod", "gin");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "dictionary_import_logs");

            migrationBuilder.DropTable(
                name: "tenant_dictionary_overrides");

            migrationBuilder.DropIndex(
                name: "IX_dictionary_items_GroupId_IsEnabled_SortOrder",
                table: "dictionary_items");

            migrationBuilder.DropIndex(
                name: "IX_dictionary_items_TenantId_GroupId_Key",
                table: "dictionary_items");

            migrationBuilder.DropIndex(
                name: "IX_dictionary_groups_TenantId_Code",
                table: "dictionary_groups");

            migrationBuilder.DropIndex(
                name: "IX_dictionary_groups_TenantId_Scope_IsEnabled",
                table: "dictionary_groups");

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

            migrationBuilder.DropColumn(
                name: "AllowOverride",
                table: "dictionary_groups");

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

            migrationBuilder.AlterColumn<string>(
                name: "Value",
                table: "dictionary_items",
                type: "character varying(256)",
                maxLength: 256,
                nullable: false,
                comment: "字典项值。",
                oldClrType: typeof(string),
                oldType: "jsonb",
                oldComment: "字典项值。");

            migrationBuilder.AlterColumn<string>(
                name: "Key",
                table: "dictionary_items",
                type: "character varying(64)",
                maxLength: 64,
                nullable: false,
                comment: "字典项键。",
                oldClrType: typeof(string),
                oldType: "character varying(128)",
                oldMaxLength: 128,
                oldComment: "字典项键。");

            migrationBuilder.AlterColumn<string>(
                name: "Code",
                table: "dictionary_groups",
                type: "character varying(64)",
                maxLength: 64,
                nullable: false,
                comment: "分组编码（唯一）。",
                oldClrType: typeof(string),
                oldType: "character varying(64)",
                oldMaxLength: 64);

            migrationBuilder.CreateIndex(
                name: "IX_dictionary_items_GroupId_Key",
                table: "dictionary_items",
                columns: new[] { "GroupId", "Key" },
                unique: true);

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