"""Update user_assigned_data_uses so it's nullable and defaults to none

Revision ID: 9caf76161e55
Revises: 918aefc950c9
Create Date: 2025-09-29 14:14:37.837616

"""

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = "9caf76161e55"
down_revision = "918aefc950c9"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column(
        "stagedresource",
        "user_assigned_data_uses",
        existing_type=postgresql.ARRAY(sa.VARCHAR()),
        nullable=True,
        server_default=None,
        default=None,
        existing_server_default=sa.text("'{}'::character varying[]"),
    )

    # Update web monitor resources with empty array to null
    op.execute(
        """
        UPDATE stagedresource
        SET user_assigned_data_uses = NULL
        WHERE
          resource_type IN ('Cookie', 'Browser request', 'Image', 'iFrame', 'Javascript tag')
          AND user_assigned_data_uses = '{}'
        """
    )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute(
        """
        UPDATE stagedresource
        SET user_assigned_data_uses = '{}'
        WHERE user_assigned_data_uses IS NULL
        """
    )

    op.alter_column(
        "stagedresource",
        "user_assigned_data_uses",
        existing_type=postgresql.ARRAY(sa.VARCHAR()),
        nullable=False,
        server_default=sa.text("'{}'::character varying[]"),
        existing_server_default=None,
        default=dict,
    )
    # ### end Alembic commands ###
