from sqlalchemy import create_engine, text
from app.config import settings

def migrate():
    engine = create_engine(settings.DATABASE_URL)
    with engine.connect() as conn:
        print("Checking for stripe_payment_id in orders...")
        try:
            # Check if column exists
            result = conn.execute(text("SELECT column_name FROM information_schema.columns WHERE table_name='orders' AND column_name='stripe_payment_id'"))
            if not result.fetchone():
                print("Adding column stripe_payment_id to orders table...")
                conn.execute(text("ALTER TABLE orders ADD COLUMN stripe_payment_id VARCHAR"))
                conn.commit()
            else:
                print("Column exists.")
        except Exception as e:
            print(f"Error migrating orders: {e}")

        print("Ensuring product_images table exists...")
        try:
            # We can use create_all here too, as it only creates missing tables
            from app.models.product import ProductImage
            from app.db.session import Base
            Base.metadata.create_all(bind=engine, tables=[ProductImage.__table__])
            print("Table verified/created.")
        except Exception as e:
            print(f"Error creating product_images: {e}")

if __name__ == "__main__":
    migrate()
