"""add docupulse settings table

Revision ID: add_docupulse_settings
Revises: add_notifs_table
Create Date: 2024-03-19 10:00:00.000000

"""
from alembic import op
import sqlalchemy as sa
from datetime import datetime
from sqlalchemy import text

# revision identifiers, used by Alembic.
revision = 'add_docupulse_settings'
down_revision = 'add_notifs_table'
branch_labels = None
depends_on = None

def upgrade():
    # Check if table exists
    conn = op.get_bind()
    inspector = sa.inspect(conn)
    if 'docupulse_settings' in inspector.get_table_names():
        # Table exists, alter the max_storage column
        op.alter_column('docupulse_settings', 'max_storage',
                       existing_type=sa.Integer(),
                       type_=sa.BigInteger(),
                       existing_nullable=False,
                       server_default='10737418240')
        
        # Check if we need to insert default data
        result = conn.execute(text("SELECT COUNT(*) FROM docupulse_settings")).scalar()
        if result == 0:
            conn.execute(text("""
                INSERT INTO docupulse_settings (id, max_rooms, max_conversations, max_storage, updated_at)
                VALUES (1, 10, 10, 10737418240, CURRENT_TIMESTAMP)
            """))
    else:
        # Create new table
        op.create_table('docupulse_settings',
            sa.Column('id', sa.Integer(), nullable=False),
            sa.Column('max_rooms', sa.Integer(), nullable=False, server_default='10'),
            sa.Column('max_conversations', sa.Integer(), nullable=False, server_default='10'),
            sa.Column('max_storage', sa.BigInteger(), nullable=False, server_default='10737418240'),  # 10GB in bytes
            sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')),
            sa.PrimaryKeyConstraint('id')
        )
        
        # Insert default settings
        op.execute(text("""
            INSERT INTO docupulse_settings (id, max_rooms, max_conversations, max_storage, updated_at)
            VALUES (1, 10, 10, 10737418240, CURRENT_TIMESTAMP)
        """))

def downgrade():
    op.drop_table('docupulse_settings') 