"""add shop subscription

Revision ID: c3f9d1cdffb4
Revises: abe5eb8acb97
Create Date: 2026-02-07 17:50:14.865261

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'c3f9d1cdffb4'
down_revision = 'abe5eb8acb97'
branch_labels = None
depends_on = None

from make_post_sell.models.meta import UUIDType


def _table_exists(name):
    conn = op.get_bind()
    result = conn.execute(
        sa.text("SELECT name FROM sqlite_master WHERE type='table' AND name=:name"),
        {"name": name},
    )
    return result.fetchone() is not None


def _column_exists(table, column):
    conn = op.get_bind()
    result = conn.execute(sa.text(f"PRAGMA table_info({table})"))
    return any(row[1] == column for row in result.fetchall())


def upgrade():
    # Add subscriptions_enabled column to shops
    if not _column_exists("mps_shop", "subscriptions_enabled"):
        op.add_column(
            "mps_shop",
            sa.Column(
                "subscriptions_enabled",
                sa.Boolean(),
                nullable=False,
                server_default="1",
            ),
        )

    # Create shop subscription table
    if not _table_exists("mps_shop_subscription"):
        op.create_table(
            "mps_shop_subscription",
            sa.Column("id", UUIDType, primary_key=True, index=True),
            sa.Column(
                "shop_id", UUIDType, sa.ForeignKey("mps_shop.id"), nullable=False, index=True
            ),
            sa.Column(
                "user_id", UUIDType, sa.ForeignKey("mps_user.id"), nullable=True, index=True
            ),
            sa.Column("email", sa.Unicode(64), nullable=False),
            sa.Column("frequency", sa.Integer(), nullable=False, server_default="1"),
            sa.Column("verified", sa.Boolean(), nullable=False, server_default="0"),
            sa.Column("unsubscribe_token", sa.Unicode(64), nullable=False, unique=True),
            sa.Column("verify_token", sa.Unicode(64), nullable=True),
            sa.Column("last_digest_timestamp", sa.BigInteger(), nullable=False),
            sa.Column("created_timestamp", sa.BigInteger(), nullable=False),
            sa.Column("disabled", sa.Boolean(), nullable=False, server_default="0"),
        )


def downgrade():
    op.drop_table("mps_shop_subscription")
    op.drop_column("mps_shop", "subscriptions_enabled")
