"""add max_bonus fields to public.organizations

Revision ID: bns001
Revises: sig001
Create Date: 2026-07-01
"""
from alembic import op
import sqlalchemy as sa

revision = 'bns001'
down_revision = 'nt001'
branch_labels = None
depends_on = None


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


def upgrade():
    conn = op.get_bind()
    if not _public_orgs_column_exists(conn, 'max_bonus_ends_at'):
        op.add_column('organizations', sa.Column('max_bonus_ends_at', sa.DateTime(), nullable=True), schema='public')
    if not _public_orgs_column_exists(conn, 'max_bonus_granted'):
        op.add_column('organizations', sa.Column('max_bonus_granted', sa.Boolean(), nullable=False, server_default=sa.text('FALSE')), schema='public')
    if not _public_orgs_column_exists(conn, 'max_bonus_last_nudge'):
        op.add_column('organizations', sa.Column('max_bonus_last_nudge', sa.Integer(), nullable=False, server_default=sa.text('0')), schema='public')


def downgrade():
    op.drop_column('organizations', 'max_bonus_last_nudge', schema='public')
    op.drop_column('organizations', 'max_bonus_granted', schema='public')
    op.drop_column('organizations', 'max_bonus_ends_at', schema='public')
