using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations
{
    /// <summary>
    /// Two covering indexes (arch-review WP1.4): <c>IX_AuditLog_OccurredAtUtc</c> gains
    /// <c>INCLUDE (Status)</c> so the audit KPI window query (count/aggregate by Status
    /// over a recent <c>OccurredAtUtc</c> range) can seek without a lookup back into the
    /// clustered index per row; <c>IX_Notifications_Delivered</c> is a new filtered index
    /// backing the notification outbox KPI's delivered-last-interval count.
    /// </summary>
    /// <remarks>
    /// <c>IX_AuditLog_OccurredAtUtc</c> is partition-aligned
    /// (<c>ON ps_AuditLog_Month(OccurredAtUtc)</c>, see <c>CollapseAuditLogToCanonical</c>)
    /// so the monthly partition-switch purge keeps touching a single partition. EF's
    /// generic <c>DropIndex</c>/<c>CreateIndex</c> migration builders have no concept of
    /// partition schemes and would silently rebuild the index off <c>[PRIMARY]</c> instead
    /// of the scheme — this migration uses raw SQL for that index (mirroring
    /// <c>CollapseAuditLogToCanonical</c>'s DDL) to preserve the alignment. The scaffolded
    /// EF model itself carries no partition annotation either way (pre-existing gap, same
    /// as every other AuditLog index) — only the physical DDL below matters.
    /// <c>Notifications</c> is not partitioned, so its index uses the ordinary EF builder.
    /// The filter predicate is a plain <c>'Delivered'</c> literal (no <c>N''</c> prefix):
    /// the value is ASCII-only, and the ConfigurationDatabase repository tests run this
    /// same filter as DDL against the SQLite provider via <c>EnsureCreated()</c>, which
    /// rejects the T-SQL national-string-literal syntax outright.
    /// </remarks>
    public partial class AddAuditLogAndNotificationCoveringIndexes : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateIndex(
                name: "IX_Notifications_Delivered",
                table: "Notifications",
                column: "DeliveredAt",
                filter: "[Status] = 'Delivered'");

            migrationBuilder.Sql(@"
DROP INDEX IX_AuditLog_OccurredAtUtc ON dbo.AuditLog;

CREATE NONCLUSTERED INDEX IX_AuditLog_OccurredAtUtc
ON dbo.AuditLog (OccurredAtUtc DESC)
INCLUDE (Status)
ON ps_AuditLog_Month(OccurredAtUtc);");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropIndex(
                name: "IX_Notifications_Delivered",
                table: "Notifications");

            migrationBuilder.Sql(@"
DROP INDEX IX_AuditLog_OccurredAtUtc ON dbo.AuditLog;

CREATE NONCLUSTERED INDEX IX_AuditLog_OccurredAtUtc
ON dbo.AuditLog (OccurredAtUtc DESC)
ON ps_AuditLog_Month(OccurredAtUtc);");
        }
    }
}
