from app import create_app, db
from sqlalchemy import text

app = create_app()

with app.app_context():
    # Add missing columns to tickets table
    try:
        with db.engine.connect() as conn:
            conn.execute(text("ALTER TABLE tickets ADD COLUMN closing_reason TEXT"))
            conn.execute(text("ALTER TABLE tickets ADD COLUMN closed_by_id INTEGER"))
            conn.execute(text("ALTER TABLE tickets ADD CONSTRAINT fk_tickets_closed_by FOREIGN KEY (closed_by_id) REFERENCES users(id)"))
            conn.commit()
            print("Added columns to tickets table.")
    except Exception as e:
        print(f"Error updating tickets table (might already exist): {e}")

    # Add is_hidden to ticket_comments table
    try:
        with db.engine.connect() as conn:
            conn.execute(text("ALTER TABLE ticket_comments ADD COLUMN is_hidden BOOLEAN DEFAULT FALSE"))
            conn.commit()
            print("Added is_hidden to ticket_comments table.")
    except Exception as e:
        print(f"Error updating ticket_comments table (might already exist): {e}")

    # Create missing tables (including link_codes)
    try:
        # This will create any missing tables, including ticket_comments and link_codes
        db.create_all()
        print("Created missing tables.")
    except Exception as e:
        print(f"Error creating tables: {e}")
