using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations
{
    /// <summary>
    /// Grants the segregated maintenance principal <c>scadabridge_audit_purger</c> the two
    /// permissions its purge path actually needs but the original role creation
    /// (<c>CollapseAuditLogToCanonical</c>) omitted (arch-review 04, S3):
    /// <list type="bullet">
    ///   <item><c>CREATE TABLE</c> — the switch-out dance CREATEs a staging table; the
    ///   role's existing <c>ALTER ON SCHEMA::dbo</c> does NOT confer the database-level
    ///   <c>CREATE TABLE</c> permission.</item>
    ///   <item><c>DELETE ON dbo.AuditLog</c> — the per-channel retention override
    ///   (<c>PurgeChannelOlderThanAsync</c>) is a bounded row DELETE on the maintenance path.</item>
    /// </list>
    /// Permission DDL only — no schema/data change. Idempotent and safe to run standalone.
    /// </summary>
    public partial class FixAuditPurgerRoleGrants : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(@"
IF DATABASE_PRINCIPAL_ID('scadabridge_audit_purger') IS NULL
    EXEC sp_executesql N'CREATE ROLE scadabridge_audit_purger';
-- The switch-out dance CREATEs a staging table; ALTER ON SCHEMA::dbo alone does not
-- confer the database-level CREATE TABLE permission (review finding S3).
GRANT CREATE TABLE TO scadabridge_audit_purger;
-- The per-channel retention override (PurgeChannelOlderThanAsync) is a bounded row
-- DELETE on the maintenance path; a segregated purger principal needs this grant.
GRANT DELETE ON dbo.AuditLog TO scadabridge_audit_purger;"); // AUDIT-PURGE-ALLOWED: role grant for the maintenance principal
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(@"
IF DATABASE_PRINCIPAL_ID('scadabridge_audit_purger') IS NOT NULL
BEGIN
    REVOKE CREATE TABLE FROM scadabridge_audit_purger;
    REVOKE DELETE ON dbo.AuditLog FROM scadabridge_audit_purger;
END"); // AUDIT-PURGE-ALLOWED: role grant reversal for the maintenance principal
        }
    }
}
