"""
Smoke tests for production health
==================================

Quick checks to verify production is working after deployment.
Run these immediately after every deploy.

Usage:
    pytest tests/smoke/ -v
    pytest tests/smoke/ --base-url=https://nordabiznes.pl
"""

import os

import pytest
import requests

pytestmark = pytest.mark.smoke

# Production URL (can be overridden by --base-url or environment variable)
PROD_URL = os.environ.get('PROD_URL', 'https://nordabiznes.pl')


class TestHealthEndpoints:
    """Tests for health check endpoints."""

    def test_health_endpoint_returns_200(self):
        """Health endpoint should return HTTP 200."""
        response = requests.get(f'{PROD_URL}/health', timeout=10)

        assert response.status_code == 200
        assert response.json().get('status') == 'ok'

    def test_health_endpoint_json_format(self):
        """Health check should return valid JSON with status field."""
        response = requests.get(f'{PROD_URL}/health', timeout=10)

        assert response.status_code == 200
        data = response.json()
        assert 'status' in data


class TestPublicPages:
    """Tests for public pages accessibility."""

    def test_homepage_loads(self):
        """Homepage should load successfully."""
        response = requests.get(PROD_URL, timeout=10)

        assert response.status_code == 200
        assert 'NordaBiz' in response.text or 'Norda' in response.text

    def test_login_page_accessible(self):
        """Login page should be accessible."""
        response = requests.get(f'{PROD_URL}/login', timeout=10)

        assert response.status_code == 200

    def test_company_catalog_loads(self):
        """Company catalog (homepage) should load."""
        # Main page IS the company catalog
        response = requests.get(PROD_URL, timeout=10)

        assert response.status_code == 200
        # Should contain company-related content
        assert 'firm' in response.text.lower() or 'company' in response.text.lower()

    def test_search_page_accessible(self):
        """Search page should be accessible."""
        response = requests.get(f'{PROD_URL}/search', timeout=10)

        assert response.status_code == 200


class TestAPIEndpoints:
    """Tests for API endpoints."""

    def test_api_companies_returns_data(self):
        """Companies API should return company data."""
        response = requests.get(f'{PROD_URL}/api/companies', timeout=10)

        assert response.status_code == 200
        data = response.json()
        # API returns dict with 'companies' key containing list
        assert 'companies' in data or isinstance(data, list)
        if 'companies' in data:
            assert isinstance(data['companies'], list)

    def test_api_search_accessible(self):
        """Search API should be accessible."""
        response = requests.get(f'{PROD_URL}/api/search?q=IT', timeout=10)

        # May return 200 or redirect, both are OK
        assert response.status_code in [200, 302, 404]


class TestSSL:
    """Tests for SSL/HTTPS configuration."""

    def test_https_redirect(self):
        """HTTP should redirect to HTTPS."""
        # Note: This may not work if HTTP is blocked at firewall level
        try:
            response = requests.get(
                PROD_URL.replace('https://', 'http://'),
                timeout=10,
                allow_redirects=False
            )
            # Should get redirect (301 or 302)
            assert response.status_code in [301, 302, 307, 308]
        except requests.exceptions.ConnectionError:
            # HTTP blocked at firewall - that's OK
            pass

    def test_https_certificate_valid(self):
        """HTTPS certificate should be valid."""
        # requests will raise SSLError if certificate is invalid
        response = requests.get(PROD_URL, timeout=10)
        assert response.status_code == 200


class TestResponseTimes:
    """Tests for response time performance."""

    def test_homepage_response_time(self):
        """Homepage should respond within 3 seconds."""
        response = requests.get(PROD_URL, timeout=10)

        assert response.elapsed.total_seconds() < 3.0

    def test_health_response_time(self):
        """Health check should respond within 1 second."""
        response = requests.get(f'{PROD_URL}/health', timeout=10)

        assert response.elapsed.total_seconds() < 1.0
