"""add instances table

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

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


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


def upgrade():
    conn = op.get_bind()
    result = conn.execute(text("""
        SELECT EXISTS (
            SELECT FROM information_schema.tables 
            WHERE table_name = 'instances'
        );
    """))
    exists = result.scalar()
    if not exists:
        op.create_table('instances',
            sa.Column('id', sa.Integer(), nullable=False),
            sa.Column('name', sa.String(length=255), nullable=False),
            sa.Column('company', sa.String(length=255), nullable=False),
            sa.Column('rooms_count', sa.Integer(), nullable=False, server_default='0'),
            sa.Column('conversations_count', sa.Integer(), nullable=False, server_default='0'),
            sa.Column('data_size', sa.String(length=50), nullable=False, server_default='0 MB'),
            sa.Column('payment_plan', sa.String(length=50), nullable=False, server_default='free'),
            sa.Column('main_url', sa.String(length=255), nullable=False),
            sa.Column('status', sa.String(length=20), nullable=False, server_default='inactive'),
            sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')),
            sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')),
            sa.PrimaryKeyConstraint('id'),
            sa.UniqueConstraint('name'),
            sa.UniqueConstraint('main_url')
        )
        
        # Create a trigger to automatically update the updated_at column
        op.execute("""
            CREATE OR REPLACE FUNCTION update_updated_at_column()
            RETURNS TRIGGER AS $$
            BEGIN
                NEW.updated_at = CURRENT_TIMESTAMP;
                RETURN NEW;
            END;
            $$ language 'plpgsql';
        """)
        
        op.execute("""
            CREATE TRIGGER update_instances_updated_at
                BEFORE UPDATE ON instances
                FOR EACH ROW
                EXECUTE FUNCTION update_updated_at_column();
        """)


def downgrade():
    op.execute("DROP TRIGGER IF EXISTS update_instances_updated_at ON instances")
    op.execute("DROP FUNCTION IF EXISTS update_updated_at_column()")
    op.drop_table('instances') 