"""
Dashboard smoke tests
=====================

Verify /dashboard renders correctly for logged-in users.

These tests seed their own user (no dependency on pre-existing test accounts)
and exercise the full rendering path, catching missing imports and template errors.
"""

import pytest
from werkzeug.security import generate_password_hash

pytestmark = pytest.mark.integration


@pytest.fixture
def dashboard_user(app):
    """Create a minimal test user directly in the DB for dashboard testing."""
    from database import SessionLocal, User

    session = SessionLocal()
    email = 'dashboard-smoke-test@nordabiznes.pl'

    # Clean up from any previous failed run
    existing = session.query(User).filter_by(email=email).first()
    if existing:
        session.delete(existing)
        session.commit()

    user = User(
        email=email,
        password_hash=generate_password_hash('SmokeDashTest!99', method='pbkdf2:sha256'),
        name='Dashboard Smoke',
        role='MEMBER',
        company_role='NONE',
        is_active=True,
        is_verified=True,
    )
    session.add(user)
    session.commit()
    user_id = user.id

    yield {'email': email, 'password': 'SmokeDashTest!99', 'id': user_id}

    # Cleanup
    session.query(User).filter_by(id=user_id).delete()
    session.commit()
    session.close()


@pytest.fixture
def dashboard_client(client, app, dashboard_user):
    """Test client logged in as the dashboard_user."""
    with app.app_context():
        response = client.post('/login', data={
            'email': dashboard_user['email'],
            'password': dashboard_user['password'],
        }, follow_redirects=True)

        # Login must succeed for these tests to be meaningful
        assert response.status_code == 200, "Login failed for dashboard smoke user"

        return client


class TestDashboardRenders:
    """Verify /dashboard renders without errors (500, NameError, etc.)."""

    def test_dashboard_returns_200(self, dashboard_client):
        """Dashboard should render successfully (not 500)."""
        response = dashboard_client.get('/dashboard')

        assert response.status_code == 200, (
            f"Dashboard returned {response.status_code}. "
            f"Response: {response.data[:500]}"
        )

    def test_dashboard_contains_expected_content(self, dashboard_client):
        """Dashboard should contain key UI elements."""
        response = dashboard_client.get('/dashboard')

        assert response.status_code == 200
        text = response.data.decode('utf-8').lower()
        # Dashboard should contain the user's name or a greeting
        assert 'dashboard' in text or 'panel' in text or 'witaj' in text

    def test_dashboard_no_server_error(self, dashboard_client):
        """Dashboard must not return any 5xx error."""
        response = dashboard_client.get('/dashboard')

        assert response.status_code < 500, (
            f"Server error on /dashboard: HTTP {response.status_code}"
        )
