"""add extra_module_slots, ai_credits_extra to orgs; add stripe_events_processed table

Revision ID: gb31a4f2e9d7
Revises: fa32b9c8d1e0
Create Date: 2026-06-11
"""
from alembic import op
import sqlalchemy as sa

revision = 'gb31a4f2e9d7'
down_revision = 'fa32b9c8d1e0'
branch_labels = None
depends_on = None


def _public_column_exists(conn, table, column):
    return conn.execute(sa.text(
        "SELECT 1 FROM information_schema.columns "
        "WHERE table_schema='public' AND table_name=:t AND column_name=:c"
    ), {"t": table, "c": column}).fetchone() is not None


def upgrade():
    # Guards: this migration targets public explicitly, but it is replayed by
    # every fresh tenant's migration run (each tenant has its own
    # alembic_version), so it must be idempotent.
    conn = op.get_bind()

    # Add extra_module_slots (Premium add-on: 1 unit = +5 slots)
    if not _public_column_exists(conn, 'organizations', 'extra_module_slots'):
        op.add_column(
            'organizations',
            sa.Column('extra_module_slots', sa.Integer(), nullable=False, server_default='0'),
            schema='public',
        )

    # Add ai_credits_extra (top-up packs; persists across billing cycles)
    if not _public_column_exists(conn, 'organizations', 'ai_credits_extra'):
        op.add_column(
            'organizations',
            sa.Column('ai_credits_extra', sa.Integer(), nullable=False, server_default='0'),
            schema='public',
        )

    # Idempotency table for one-time Stripe events (e.g. checkout.session.completed)
    exists = conn.execute(sa.text(
        "SELECT 1 FROM information_schema.tables "
        "WHERE table_schema='public' AND table_name='stripe_events_processed'"
    )).fetchone()
    if not exists:
        op.create_table(
            'stripe_events_processed',
            sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
            sa.Column('event_id', sa.String(255), nullable=False),
            sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.text('NOW()')),
            sa.PrimaryKeyConstraint('id'),
            sa.UniqueConstraint('event_id'),
            schema='public',
        )


def downgrade():
    op.drop_table('stripe_events_processed', schema='public')
    op.drop_column('organizations', 'ai_credits_extra', schema='public')
    op.drop_column('organizations', 'extra_module_slots', schema='public')
