"""Add INTUNE asset source + intune_device_id / defender_machine_id

Revision ID: 033
Revises: 032
Create Date: 2026-06-14 09:00:00.000000

Microsoft Intune (MDM/UEM) as a third inventory source next to Wazuh and
Nessus. Adds the enum label + the pin columns used to reconnect an asset to
its Intune managedDevice and (phase 3) its Defender for Endpoint machine.

ALTER TYPE ... ADD VALUE cannot run inside a transaction block on older
Postgres → autocommit_block. Idempotent (IF NOT EXISTS).
"""
from alembic import op


revision = "033"
down_revision = "032"
branch_labels = None
depends_on = None


def upgrade() -> None:
    with op.get_context().autocommit_block():
        op.execute("ALTER TYPE assetsource ADD VALUE IF NOT EXISTS 'INTUNE'")
    op.execute("""
        ALTER TABLE assets
            ADD COLUMN IF NOT EXISTS intune_device_id    VARCHAR(64),
            ADD COLUMN IF NOT EXISTS defender_machine_id VARCHAR(64);
    """)
    op.execute("CREATE INDEX IF NOT EXISTS ix_assets_intune_device_id ON assets (intune_device_id);")
    op.execute("CREATE INDEX IF NOT EXISTS ix_assets_defender_machine_id ON assets (defender_machine_id);")


def downgrade() -> None:
    op.execute("DROP INDEX IF EXISTS ix_assets_intune_device_id;")
    op.execute("DROP INDEX IF EXISTS ix_assets_defender_machine_id;")
    op.execute("""
        ALTER TABLE assets
            DROP COLUMN IF EXISTS intune_device_id,
            DROP COLUMN IF EXISTS defender_machine_id;
    """)
