"""Add scopes field to user_sessions table

Revision ID: d784000f1f80
Revises: 503b06c92be0
Create Date: 2025-08-21 14:54:29.966957

"""

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

# Polar Custom Imports
from polar.kit.extensions.sqlalchemy import StringEnum

# revision identifiers, used by Alembic.
revision = "d784000f1f80"
down_revision = "503b06c92be0"
branch_labels: tuple[str] | None = None
depends_on: tuple[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # Add column with server default first (for existing rows)
    op.add_column(
        "user_sessions",
        sa.Column(
            "scopes",
            postgresql.ARRAY(sa.String()),
            nullable=False,
            server_default="{}",
        ),
    )

    # Update existing rows to have web:write scope
    op.execute("""
        UPDATE user_sessions 
        SET scopes = ARRAY['web:read', 'web:write']
        WHERE scopes = '{}'
    """)

    # Remove the server default
    op.alter_column("user_sessions", "scopes", server_default=None)
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("user_sessions", "scopes")
    # ### end Alembic commands ###
