using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace SolutionErp.Infrastructure.Persistence.Migrations
{
    /// <inheritdoc />
    public partial class AddPeMultiWinnerAndLevelFinalize : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<bool>(
                name: "IsWinner",
                table: "PurchaseEvaluationSuppliers",
                type: "bit",
                nullable: false,
                defaultValue: false);

            migrationBuilder.AddColumn<bool>(
                name: "AllowApproverFinalize",
                table: "ApprovalWorkflowLevels",
                type: "bit",
                nullable: false,
                defaultValue: false);

            // [Mig 58] Backfill IsWinner từ winner đơn lẻ cũ (SelectedSupplierId) —
            // phiếu UAT đang chạy giữ winner đã chọn dưới mô hình multi-winner mới.
            // Chạy SAU AddColumn (cột đã tồn tại). Idempotent: chỉ set 1 (default 0
            // không đụng) → re-run no-op. KHÔNG un-backfill ở Down (DropColumn xoá hẳn).
            migrationBuilder.Sql(@"
UPDATE pes SET IsWinner = 1
FROM PurchaseEvaluationSuppliers pes
INNER JOIN PurchaseEvaluations pe ON pe.Id = pes.PurchaseEvaluationId
WHERE pe.SelectedSupplierId IS NOT NULL AND pes.SupplierId = pe.SelectedSupplierId;");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "IsWinner",
                table: "PurchaseEvaluationSuppliers");

            migrationBuilder.DropColumn(
                name: "AllowApproverFinalize",
                table: "ApprovalWorkflowLevels");
        }
    }
}
