using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace SolutionErp.Infrastructure.Persistence.Migrations
{
    /// <inheritdoc />
    public partial class ReplaceBudgetModuleWithPeWorkItemBudgets : Migration
    {
        /// <inheritdoc />
        // [S61 Mig 50] Reorder TAY theo advise database-agent (scaffold mặc định
        // drop-trước-add; RIÊNG RenameColumn EF tự đoán BudgetManualAmount →
        // ExpectedRemainingAmount là SAI SEMANTICS — số nhập tay cũ phải migrate
        // sang BudgetPeriodAmount "NS kỳ này" row 3, không phải "dự kiến còn lại"
        // row 8): (1) AddColumn mới → (2) Sql UPDATE backfill (4 phiếu UAT thật
        // PE/2026/A/001+ GIỮ SỐ) → (3) DropIndex trước DropColumn (SQL 5074) →
        // (4) DropColumn cũ → (5) DropTable 5 bảng children-first (4 FK đều khai
        // trên child, CASCADE — không cần DropForeignKey riêng) → (6) CreateTable
        // mới → (7) Sql DELETE menu/permission (IN-list tường minh — LIKE 'Bg_%'
        // dính bẫy underscore-wildcard T-SQL + miss root 'Budgets').
        // Precedent data-migrate cùng shape: 20260513130144 (add→backfill→drop).
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            // (1) 2 cột ngân sách mới trên PE
            migrationBuilder.AddColumn<decimal>(
                name: "BudgetPeriodAmount",
                table: "PurchaseEvaluations",
                type: "decimal(18,2)",
                precision: 18,
                scale: 2,
                nullable: true);

            migrationBuilder.AddColumn<decimal>(
                name: "ExpectedRemainingAmount",
                table: "PurchaseEvaluations",
                type: "decimal(18,2)",
                precision: 18,
                scale: 2,
                nullable: true);

            // (2) Backfill: số ngân sách nhập tay cũ = "NS kỳ này" của phiếu
            migrationBuilder.Sql(
                "UPDATE [PurchaseEvaluations] SET [BudgetPeriodAmount] = [BudgetManualAmount] WHERE [BudgetManualAmount] IS NOT NULL;");

            // (3) DropIndex TRƯỚC DropColumn (SQL Server error 5074 nếu ngược)
            migrationBuilder.DropIndex(
                name: "IX_PurchaseEvaluations_BudgetId",
                table: "PurchaseEvaluations");

            migrationBuilder.DropIndex(
                name: "IX_Contracts_BudgetId",
                table: "Contracts");

            // (4) Drop cột cũ (PE 3 cột; Contracts CHỈ BudgetId — BudgetManual*
            // của HĐ GIỮ NGUYÊN, anh Kiệt chỉ redesign ngân sách PE)
            migrationBuilder.DropColumn(
                name: "BudgetId",
                table: "PurchaseEvaluations");

            migrationBuilder.DropColumn(
                name: "BudgetManualName",
                table: "PurchaseEvaluations");

            migrationBuilder.DropColumn(
                name: "BudgetManualAmount",
                table: "PurchaseEvaluations");

            migrationBuilder.DropColumn(
                name: "BudgetId",
                table: "Contracts");

            // (5) Drop 5 bảng module Budget cũ — children-first
            migrationBuilder.DropTable(
                name: "BudgetApprovals");

            migrationBuilder.DropTable(
                name: "BudgetChangelogs");

            migrationBuilder.DropTable(
                name: "BudgetDepartmentApprovals");

            migrationBuilder.DropTable(
                name: "BudgetDetails");

            migrationBuilder.DropTable(
                name: "Budgets");

            migrationBuilder.CreateTable(
                name: "PeWorkItemBudgets",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    ProjectId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    WorkItemId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    ProEstimateAmount = table.Column<decimal>(type: "decimal(18,2)", precision: 18, scale: 2, nullable: true),
                    ProNote = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: true),
                    InitialAmount = table.Column<decimal>(type: "decimal(18,2)", precision: 18, scale: 2, nullable: true),
                    AdjustmentAmount = table.Column<decimal>(type: "decimal(18,2)", precision: 18, scale: 2, nullable: true),
                    CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
                    UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    CreatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    UpdatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    IsDeleted = table.Column<bool>(type: "bit", nullable: false),
                    DeletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    DeletedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_PeWorkItemBudgets", x => x.Id);
                });

            migrationBuilder.CreateIndex(
                name: "IX_PeWorkItemBudgets_ProjectId_WorkItemId",
                table: "PeWorkItemBudgets",
                columns: new[] { "ProjectId", "WorkItemId" },
                unique: true,
                filter: "[IsDeleted] = 0");

            migrationBuilder.CreateIndex(
                name: "IX_PeWorkItemBudgets_WorkItemId",
                table: "PeWorkItemBudgets",
                column: "WorkItemId");

            // (7) Dọn menu + permission module cũ. IN-list tường minh (advise
            // database-agent: Permissions key theo MenuKey string FK CASCADE →
            // MenuItems; MenuItems self-FK ParentKey RESTRICT → children TRƯỚC
            // root SAU). DELETE idempotent tự nhiên.
            migrationBuilder.Sql(
                "DELETE FROM [Permissions] WHERE [MenuKey] IN ('Budgets','Bg_List','Bg_Create','Bg_Pending');");
            migrationBuilder.Sql(
                "DELETE FROM [MenuItems] WHERE [Key] IN ('Bg_List','Bg_Create','Bg_Pending');");
            migrationBuilder.Sql(
                "DELETE FROM [MenuItems] WHERE [Key] = 'Budgets';");
        }

        /// <inheritdoc />
        // [S61] Down tái tạo SCHEMA đầy đủ (5 bảng + FK + index + cột cũ) nhưng
        // KHÔNG khôi phục data Budget cũ + menu/permission rows đã DELETE —
        // (data-loss one-way chấp nhận, anh Kiệt chốt "xóa hẳn module").
        // BudgetPeriodAmount backfill ngược về BudgetManualAmount để số phiếu
        // không mất khi rollback.
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "PeWorkItemBudgets");

            migrationBuilder.AddColumn<decimal>(
                name: "BudgetManualAmount",
                table: "PurchaseEvaluations",
                type: "decimal(18,2)",
                precision: 18,
                scale: 2,
                nullable: true);

            migrationBuilder.Sql(
                "UPDATE [PurchaseEvaluations] SET [BudgetManualAmount] = [BudgetPeriodAmount] WHERE [BudgetPeriodAmount] IS NOT NULL;");

            migrationBuilder.DropColumn(
                name: "BudgetPeriodAmount",
                table: "PurchaseEvaluations");

            migrationBuilder.DropColumn(
                name: "ExpectedRemainingAmount",
                table: "PurchaseEvaluations");

            migrationBuilder.AddColumn<Guid>(
                name: "BudgetId",
                table: "PurchaseEvaluations",
                type: "uniqueidentifier",
                nullable: true);

            migrationBuilder.AddColumn<string>(
                name: "BudgetManualName",
                table: "PurchaseEvaluations",
                type: "nvarchar(200)",
                maxLength: 200,
                nullable: true);

            migrationBuilder.AddColumn<Guid>(
                name: "BudgetId",
                table: "Contracts",
                type: "uniqueidentifier",
                nullable: true);

            migrationBuilder.CreateTable(
                name: "Budgets",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
                    CreatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    DeletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    DeletedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    DepartmentId = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    Description = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: true),
                    DrafterUserId = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    IsDeleted = table.Column<bool>(type: "bit", nullable: false),
                    MaNganSach = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true),
                    NamNganSach = table.Column<int>(type: "int", nullable: false),
                    Phase = table.Column<int>(type: "int", nullable: false),
                    ProjectId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    RejectedFromPhase = table.Column<int>(type: "int", nullable: true),
                    SlaDeadline = table.Column<DateTime>(type: "datetime2", nullable: true),
                    SlaWarningSent = table.Column<bool>(type: "bit", nullable: false),
                    TenNganSach = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: false),
                    TongNganSach = table.Column<decimal>(type: "decimal(18,2)", precision: 18, scale: 2, nullable: false),
                    UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    UpdatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Budgets", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "BudgetApprovals",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    BudgetId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    ApprovedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
                    ApproverUserId = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    Comment = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: true),
                    CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
                    CreatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    Decision = table.Column<int>(type: "int", nullable: false),
                    FromPhase = table.Column<int>(type: "int", nullable: false),
                    ToPhase = table.Column<int>(type: "int", nullable: false),
                    UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    UpdatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_BudgetApprovals", x => x.Id);
                    table.ForeignKey(
                        name: "FK_BudgetApprovals_Budgets_BudgetId",
                        column: x => x.BudgetId,
                        principalTable: "Budgets",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "BudgetChangelogs",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    BudgetId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    Action = table.Column<int>(type: "int", nullable: false),
                    ContextNote = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: true),
                    CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
                    CreatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    EntityId = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    EntityType = table.Column<int>(type: "int", nullable: false),
                    FieldChangesJson = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    PhaseAtChange = table.Column<int>(type: "int", nullable: true),
                    Summary = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: true),
                    UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    UpdatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    UserName = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_BudgetChangelogs", x => x.Id);
                    table.ForeignKey(
                        name: "FK_BudgetChangelogs_Budgets_BudgetId",
                        column: x => x.BudgetId,
                        principalTable: "Budgets",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "BudgetDepartmentApprovals",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    BudgetId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    ApprovedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
                    ApproverRoleSnapshot = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true),
                    ApproverUserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    Comment = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: true),
                    CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
                    CreatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    DeletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    DeletedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    DepartmentId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    IsBypassed = table.Column<bool>(type: "bit", nullable: false),
                    IsDeleted = table.Column<bool>(type: "bit", nullable: false),
                    PhaseAtApproval = table.Column<int>(type: "int", nullable: false),
                    Stage = table.Column<int>(type: "int", nullable: false),
                    UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    UpdatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_BudgetDepartmentApprovals", x => x.Id);
                    table.ForeignKey(
                        name: "FK_BudgetDepartmentApprovals_Budgets_BudgetId",
                        column: x => x.BudgetId,
                        principalTable: "Budgets",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "BudgetDetails",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    BudgetId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
                    CreatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
                    DonGia = table.Column<decimal>(type: "decimal(18,2)", precision: 18, scale: 2, nullable: false),
                    DonViTinh = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true),
                    GhiChu = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: true),
                    GroupCode = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
                    GroupName = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false),
                    ItemCode = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true),
                    KhoiLuong = table.Column<decimal>(type: "decimal(18,4)", precision: 18, scale: 4, nullable: false),
                    NoiDung = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: false),
                    Order = table.Column<int>(type: "int", nullable: false),
                    ThanhTien = table.Column<decimal>(type: "decimal(18,2)", precision: 18, scale: 2, nullable: false),
                    UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    UpdatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_BudgetDetails", x => x.Id);
                    table.ForeignKey(
                        name: "FK_BudgetDetails_Budgets_BudgetId",
                        column: x => x.BudgetId,
                        principalTable: "Budgets",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_PurchaseEvaluations_BudgetId",
                table: "PurchaseEvaluations",
                column: "BudgetId");

            migrationBuilder.CreateIndex(
                name: "IX_Contracts_BudgetId",
                table: "Contracts",
                column: "BudgetId");

            migrationBuilder.CreateIndex(
                name: "IX_BudgetApprovals_BudgetId_ApprovedAt",
                table: "BudgetApprovals",
                columns: new[] { "BudgetId", "ApprovedAt" });

            migrationBuilder.CreateIndex(
                name: "IX_BudgetChangelogs_BudgetId_CreatedAt",
                table: "BudgetChangelogs",
                columns: new[] { "BudgetId", "CreatedAt" });

            migrationBuilder.CreateIndex(
                name: "IX_BudgetChangelogs_BudgetId_EntityType",
                table: "BudgetChangelogs",
                columns: new[] { "BudgetId", "EntityType" });

            migrationBuilder.CreateIndex(
                name: "IX_BudgetDepartmentApprovals_ApproverUserId",
                table: "BudgetDepartmentApprovals",
                column: "ApproverUserId");

            migrationBuilder.CreateIndex(
                name: "IX_BudgetDepartmentApprovals_BudgetId",
                table: "BudgetDepartmentApprovals",
                column: "BudgetId");

            migrationBuilder.CreateIndex(
                name: "IX_BudgetDepartmentApprovals_DepartmentId",
                table: "BudgetDepartmentApprovals",
                column: "DepartmentId");

            migrationBuilder.CreateIndex(
                name: "UX_BudgetDeptApprovals_Budget_Phase_Dept_Stage",
                table: "BudgetDepartmentApprovals",
                columns: new[] { "BudgetId", "PhaseAtApproval", "DepartmentId", "Stage" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_BudgetDetails_BudgetId_Order",
                table: "BudgetDetails",
                columns: new[] { "BudgetId", "Order" });

            migrationBuilder.CreateIndex(
                name: "IX_Budgets_MaNganSach",
                table: "Budgets",
                column: "MaNganSach",
                unique: true,
                filter: "[MaNganSach] IS NOT NULL");

            migrationBuilder.CreateIndex(
                name: "IX_Budgets_NamNganSach",
                table: "Budgets",
                column: "NamNganSach");

            migrationBuilder.CreateIndex(
                name: "IX_Budgets_Phase_IsDeleted",
                table: "Budgets",
                columns: new[] { "Phase", "IsDeleted" });

            migrationBuilder.CreateIndex(
                name: "IX_Budgets_ProjectId",
                table: "Budgets",
                column: "ProjectId");

            migrationBuilder.CreateIndex(
                name: "IX_Budgets_SlaDeadline",
                table: "Budgets",
                column: "SlaDeadline");
        }
    }
}
