using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace SolutionErp.Infrastructure.Persistence.Migrations
{
    /// <inheritdoc />
    public partial class AddPeApprovedBudgetSnapshot : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<decimal>(
                name: "ApprovedBudgetCcmAdjustmentAmount",
                table: "PurchaseEvaluations",
                type: "decimal(18,2)",
                precision: 18,
                scale: 2,
                nullable: true);

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

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

            migrationBuilder.AddColumn<int>(
                name: "ApprovedBudgetPrevSelectedCount",
                table: "PurchaseEvaluations",
                type: "int",
                nullable: true);

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

            migrationBuilder.AddColumn<int>(
                name: "ApprovedBudgetPrevSubmittedCount",
                table: "PurchaseEvaluations",
                type: "int",
                nullable: true);

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

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

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

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

            migrationBuilder.AddColumn<DateTime>(
                name: "ApprovedBudgetSnapshotAt",
                table: "PurchaseEvaluations",
                type: "datetime2",
                nullable: true);

            // [S133 2026-07-17 — anh Kiệt FDC] Backfill snapshot ngân sách cho phiếu ĐÃ DUYỆT
            // hiện hữu = giá trị LIVE hôm nay (số tại-thời-điểm-duyệt KHÔNG khôi phục được —
            // Changelogs có log budget-edit nhưng gắn phiếu-đang-mở-lúc-sửa, attribution gap).
            // Idempotent: WHERE ApprovedBudgetSnapshotAt IS NULL → re-run no-op. SQL-Server-only
            // (tests SQLite EnsureCreated KHÔNG replay migration — mirror Mig 61/65).
            // Predicate lũy kế = BẢN DỊCH SQL của PeBudgetAccumulator.ComputeAsync (3 bản phải khớp:
            // SQL này ↔ accumulator ↔ GetPurchaseEvaluationQuery cũ): peers cùng (ProjectId, WorkItemId),
            // Id <> pe, CreatedAt < pe, IsDeleted = 0; submitted = Phase IN (10 ChoDuyet, 7 DaDuyet);
            // selected = Phase 7 + EXISTS supplier IsWinner. Suppliers/Quotes = BaseEntity KHÔNG
            // soft-delete filter → không điều kiện IsDeleted trên s/q. Phiếu WorkItemId NULL →
            // 6 cột pair NULL (LEFT JOIN không match) + 4 lũy kế NULL (CASE — mirror helper runtime),
            // SnapshotAt VẪN set (marker "đã chốt").
            migrationBuilder.Sql(@"
UPDATE pe SET
    ApprovedBudgetProInitialAmount    = b.ProInitialAmount,
    ApprovedBudgetProAdjustmentAmount = b.ProAdjustmentAmount,
    ApprovedBudgetProNote             = b.ProNote,
    ApprovedBudgetCcmInitialAmount    = b.InitialAmount,
    ApprovedBudgetCcmAdjustmentAmount = b.AdjustmentAmount,
    ApprovedBudgetCcmNote             = b.CcmNote,
    ApprovedBudgetPrevSubmittedTotal  = CASE WHEN pe.WorkItemId IS NULL THEN NULL ELSE ISNULL(sub.SubmittedTotal, 0) END,
    ApprovedBudgetPrevSubmittedCount  = CASE WHEN pe.WorkItemId IS NULL THEN NULL ELSE ISNULL(sub.SubmittedCount, 0) END,
    ApprovedBudgetPrevSelectedTotal   = CASE WHEN pe.WorkItemId IS NULL THEN NULL ELSE ISNULL(selt.SelectedTotal, 0) END,
    ApprovedBudgetPrevSelectedCount   = CASE WHEN pe.WorkItemId IS NULL THEN NULL ELSE ISNULL(sel.SelectedCount, 0) END,
    ApprovedBudgetSnapshotAt          = SYSUTCDATETIME()
FROM PurchaseEvaluations pe
LEFT JOIN PeWorkItemBudgets b
       ON b.ProjectId = pe.ProjectId AND b.WorkItemId = pe.WorkItemId AND b.IsDeleted = 0
OUTER APPLY (
    SELECT COUNT(*) AS SubmittedCount,
           SUM(ISNULL(p.BudgetPeriodAmount, 0)) AS SubmittedTotal
    FROM PurchaseEvaluations p
    WHERE p.ProjectId = pe.ProjectId AND p.WorkItemId = pe.WorkItemId
      AND p.Id <> pe.Id AND p.CreatedAt < pe.CreatedAt AND p.IsDeleted = 0
      AND p.Phase IN (10, 7)
) sub
OUTER APPLY (
    SELECT COUNT(*) AS SelectedCount
    FROM PurchaseEvaluations p
    WHERE p.ProjectId = pe.ProjectId AND p.WorkItemId = pe.WorkItemId
      AND p.Id <> pe.Id AND p.CreatedAt < pe.CreatedAt AND p.IsDeleted = 0
      AND p.Phase = 7
      AND EXISTS (SELECT 1 FROM PurchaseEvaluationSuppliers s
                  WHERE s.PurchaseEvaluationId = p.Id AND s.IsWinner = 1)
) sel
OUTER APPLY (
    SELECT SUM(q.ThanhTien) AS SelectedTotal
    FROM PurchaseEvaluations p
    INNER JOIN PurchaseEvaluationSuppliers s ON s.PurchaseEvaluationId = p.Id
    INNER JOIN PurchaseEvaluationQuotes q ON q.PurchaseEvaluationSupplierId = s.Id
    WHERE p.ProjectId = pe.ProjectId AND p.WorkItemId = pe.WorkItemId
      AND p.Id <> pe.Id AND p.CreatedAt < pe.CreatedAt AND p.IsDeleted = 0
      AND p.Phase = 7 AND q.IsSelected = 1
      AND EXISTS (SELECT 1 FROM PurchaseEvaluationSuppliers s2
                  WHERE s2.PurchaseEvaluationId = p.Id AND s2.IsWinner = 1)
) selt
WHERE pe.Phase = 7 AND pe.ApprovedBudgetSnapshotAt IS NULL AND pe.IsDeleted = 0;");
        }

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

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

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

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

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

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

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

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

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

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

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