import pytest
import os
from app import create_app, db

def test_production_config():
    """Test production configuration settings."""
    app = create_app('production')
    
    # Test essential production settings
    assert not app.config['DEBUG']
    assert app.config['TESTING'] is False
    assert 'SECRET_KEY' in app.config
    assert app.config['SQLALCHEMY_DATABASE_URI'] is not None
    assert app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] is False

def test_database_connection(app):
    """Test database connection in production environment."""
    with app.app_context():
        try:
            # Test database connection
            db.engine.connect()
            assert True
        except Exception as e:
            pytest.fail(f"Database connection failed: {str(e)}")

def test_environment_variables():
    """Test required environment variables are set."""
    required_vars = [
        'FLASK_APP',
        'FLASK_ENV',
        'SECRET_KEY',
        'DATABASE_URL'
    ]
    
    for var in required_vars:
        assert os.getenv(var) is not None, f"Required environment variable {var} is not set"

def test_gunicorn_config():
    """Test Gunicorn configuration settings."""
    import gunicorn_config
    
    assert hasattr(gunicorn_config, 'bind')
    assert hasattr(gunicorn_config, 'workers')
    assert hasattr(gunicorn_config, 'timeout')
    assert gunicorn_config.forwarded_allow_ips != '*'

def test_container_health_check(client):
    """Test container health check endpoint."""
    response = client.get('/health')
    assert response.status_code == 200
    assert response.json['status'] == 'healthy'

def test_error_handling(client):
    """Test error handling for common deployment issues."""
    # Test database connection error
    with pytest.raises(Exception):
        client.get('/calculator')
    
    # Test rate limiting
    for _ in range(100):
        client.get('/')
    
    response = client.get('/')
    assert response.status_code == 429  # Too Many Requests 