"""rename userdetail to user_details

Revision ID: e8901fg2345
Revises: d7890ef1234
Create Date: 2025-01-17 12:30:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = 'e8901fg2345'
down_revision: Union[str, None] = 'd7890ef1234'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """
    Rename userdetail table to user_details
    """
    # Check if table exists
    conn = op.get_bind()
    inspector = sa.inspect(conn)
    tables = inspector.get_table_names()
    
    if 'userdetail' in tables:
        # Rename table
        op.rename_table('userdetail', 'user_details')
    elif 'user_details' not in tables:
        # Table doesn't exist, create it fresh (shouldn't happen, but safety check)
        op.create_table('user_details',
            sa.Column('id', sa.Integer(), nullable=False),
            sa.Column('username', sa.String(), nullable=True),
            sa.Column('name', sa.String(), nullable=True),
            sa.Column('user_id', sa.Integer(), nullable=True),
            sa.Column('timezone', sa.String(), nullable=True),
            sa.Column('token', sa.String(), nullable=True),
            sa.Column('org_id', sa.Integer(), nullable=True),
            sa.Column('sd_token', sa.Integer(), nullable=True),
            sa.Column('bucket', sa.String(), nullable=True),
            sa.Column('timestamp', sa.DateTime(), nullable=True),
            sa.PrimaryKeyConstraint('id')
        )


def downgrade() -> None:
    """
    Revert user_details table back to userdetail
    """
    conn = op.get_bind()
    inspector = sa.inspect(conn)
    tables = inspector.get_table_names()
    
    if 'user_details' in tables:
        # Rename table back
        op.rename_table('user_details', 'userdetail')

