BEGIN TRANSACTION;
IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N'20260709105112_FixAuditPurgerRoleGrants'
)
BEGIN

    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;
END;

IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N'20260709105112_FixAuditPurgerRoleGrants'
)
BEGIN
    INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
    VALUES (N'20260709105112_FixAuditPurgerRoleGrants', N'10.0.7');
END;

COMMIT;
GO

