"""
Test Suite for Premium Rebrand - Iteration 5
Testing: VIN Search (hero/navbar), Manual Search, Inventory, Find Part page,
User Dashboard, Admin Dashboard, How It Works, Contact, About, Footer
"""
import pytest
import requests
import os

BASE_URL = os.environ.get('REACT_APP_BACKEND_URL', '').rstrip('/')
if not BASE_URL:
    BASE_URL = "https://wholesale-auto-parts.preview.emergentagent.com"


# --- Test Fixtures ---
@pytest.fixture
def api_client():
    """Shared requests session"""
    session = requests.Session()
    session.headers.update({"Content-Type": "application/json"})
    return session


@pytest.fixture
def admin_token(api_client):
    """Get admin authentication token"""
    response = api_client.post(f"{BASE_URL}/api/auth/login", json={
        "username": "admin",
        "password": "queencity2024"
    })
    if response.status_code == 200:
        return response.json().get("token")
    pytest.skip("Admin authentication failed - skipping admin tests")


@pytest.fixture
def user_token(api_client):
    """Get or create user authentication token"""
    # Try login first
    response = api_client.post(f"{BASE_URL}/api/user/login", json={
        "email": "test@test.com",
        "password": "test123"
    })
    if response.status_code == 200:
        return response.json().get("token")
    
    # Try register
    response = api_client.post(f"{BASE_URL}/api/user/register", json={
        "name": "Test User",
        "email": "test@test.com",
        "password": "test123",
        "phone": "704-555-1234"
    })
    if response.status_code == 200:
        return response.json().get("token")
    
    # Retry login after register
    response = api_client.post(f"{BASE_URL}/api/user/login", json={
        "email": "test@test.com",
        "password": "test123"
    })
    if response.status_code == 200:
        return response.json().get("token")
    
    pytest.skip("User authentication failed - skipping user tests")


class TestPublicAPIs:
    """Test public API endpoints (no auth required)"""

    def test_inventory_list(self, api_client):
        """Test GET /api/inventory returns parts list"""
        response = api_client.get(f"{BASE_URL}/api/inventory")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        if len(data) > 0:
            item = data[0]
            # Verify part structure - needed for product grid
            assert "id" in item
            assert "name" in item
            assert "price" in item
            assert "condition" in item
            print(f"✓ Inventory API works: {len(data)} parts returned")

    def test_inventory_has_condition_field(self, api_client):
        """Verify condition badges work - parts have condition field"""
        response = api_client.get(f"{BASE_URL}/api/inventory")
        assert response.status_code == 200
        data = response.json()
        if len(data) > 0:
            # Check first item has condition for badge display
            item = data[0]
            assert "condition" in item
            # Conditions should be: New, OEM, OEM Used, Used, Refurbished
            print(f"✓ Part condition: {item.get('condition')}")

    def test_vin_decode_valid(self, api_client):
        """Test VIN decode API with valid VIN"""
        # Test VIN: 2018 Honda Accord
        test_vin = "1HGCV1F34JA004035"
        response = api_client.get(f"{BASE_URL}/api/vin-decode/{test_vin}")
        assert response.status_code == 200
        data = response.json()
        # Verify VIN decode returns year/make/model for search
        assert "year" in data
        assert "make" in data
        assert "model" in data
        print(f"✓ VIN decode works: {data.get('year')} {data.get('make')} {data.get('model')}")

    def test_vin_decode_invalid_length(self, api_client):
        """Test VIN decode rejects invalid VIN length"""
        response = api_client.get(f"{BASE_URL}/api/vin-decode/SHORT123")
        assert response.status_code == 400
        print("✓ VIN decode rejects short VIN")

    def test_part_request_create_anonymous(self, api_client):
        """Test anonymous part request submission"""
        response = api_client.post(f"{BASE_URL}/api/part-requests", json={
            "vehicle_year": "2020",
            "make": "Toyota",
            "model": "Camry",
            "part_needed": "Driver side mirror",
            "name": "Test Anonymous",
            "email": "anon@test.com",
            "phone": "555-1234"
        })
        assert response.status_code == 200
        data = response.json()
        assert data.get("status") == "new"
        assert data.get("part_needed") == "Driver side mirror"
        print(f"✓ Anonymous part request created: {data.get('id')}")

    def test_contact_form_submit(self, api_client):
        """Test contact form submission"""
        response = api_client.post(f"{BASE_URL}/api/contact", json={
            "name": "Contact Test",
            "email": "contact@test.com",
            "phone": "555-9999",
            "message": "Testing contact form"
        })
        assert response.status_code == 200
        data = response.json()
        assert "id" in data
        print(f"✓ Contact form submitted: {data.get('id')}")

    def test_testimonials_list(self, api_client):
        """Test testimonials endpoint"""
        response = api_client.get(f"{BASE_URL}/api/testimonials")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ Testimonials API works: {len(data)} testimonials")


class TestUserAuth:
    """Test user authentication flow"""

    def test_user_login_valid(self, api_client):
        """Test user login with valid credentials"""
        # First ensure user exists
        api_client.post(f"{BASE_URL}/api/user/register", json={
            "name": "Test User",
            "email": "test@test.com",
            "password": "test123",
            "phone": ""
        })
        
        # Now login
        response = api_client.post(f"{BASE_URL}/api/user/login", json={
            "email": "test@test.com",
            "password": "test123"
        })
        assert response.status_code == 200
        data = response.json()
        assert "token" in data
        assert "user" in data
        assert data["user"]["email"] == "test@test.com"
        print(f"✓ User login works: {data['user']['name']}")

    def test_user_login_invalid(self, api_client):
        """Test user login with invalid credentials"""
        response = api_client.post(f"{BASE_URL}/api/user/login", json={
            "email": "wrong@test.com",
            "password": "wrongpass"
        })
        assert response.status_code == 401
        print("✓ Invalid login rejected")


class TestUserDashboard:
    """Test user dashboard APIs"""

    def test_user_overview(self, api_client, user_token):
        """Test user overview/stats endpoint"""
        api_client.headers.update({"Authorization": f"Bearer {user_token}"})
        response = api_client.get(f"{BASE_URL}/api/user/overview")
        assert response.status_code == 200
        data = response.json()
        # Verify overview structure for dashboard
        assert "active_orders" in data
        assert "pending_quotes" in data
        assert "unpaid_invoices_count" in data
        assert "vehicles_count" in data
        assert "recent_requests" in data
        assert "recent_shipments" in data
        print(f"✓ User overview works: {data.get('active_orders')} active orders")

    def test_user_part_requests(self, api_client, user_token):
        """Test user part requests list"""
        api_client.headers.update({"Authorization": f"Bearer {user_token}"})
        response = api_client.get(f"{BASE_URL}/api/user/part-requests")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ User requests API works: {len(data)} requests")

    def test_user_vehicles_crud(self, api_client, user_token):
        """Test user vehicles (My Garage) CRUD"""
        api_client.headers.update({"Authorization": f"Bearer {user_token}"})
        
        # CREATE vehicle
        response = api_client.post(f"{BASE_URL}/api/user/vehicles", json={
            "year": "2022",
            "make": "Honda",
            "model": "Accord",
            "vin": "1HGCV1F34NA000001",
            "engine": "2.0L Turbo",
            "trim": "Sport",
            "nickname": "Daily Driver"
        })
        assert response.status_code == 200
        vehicle = response.json()
        vehicle_id = vehicle.get("id")
        assert vehicle["year"] == "2022"
        print(f"✓ Vehicle created: {vehicle_id}")
        
        # LIST vehicles
        response = api_client.get(f"{BASE_URL}/api/user/vehicles")
        assert response.status_code == 200
        vehicles = response.json()
        assert len(vehicles) > 0
        print(f"✓ Vehicles listed: {len(vehicles)} vehicles")
        
        # UPDATE vehicle
        response = api_client.patch(f"{BASE_URL}/api/user/vehicles/{vehicle_id}", json={
            "nickname": "Updated Nickname"
        })
        assert response.status_code == 200
        updated = response.json()
        assert updated["nickname"] == "Updated Nickname"
        print(f"✓ Vehicle updated")
        
        # DELETE vehicle
        response = api_client.delete(f"{BASE_URL}/api/user/vehicles/{vehicle_id}")
        assert response.status_code == 200
        print(f"✓ Vehicle deleted")

    def test_user_quotes_list(self, api_client, user_token):
        """Test user quotes list"""
        api_client.headers.update({"Authorization": f"Bearer {user_token}"})
        response = api_client.get(f"{BASE_URL}/api/user/quotes")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ User quotes API works: {len(data)} quotes")

    def test_user_orders_list(self, api_client, user_token):
        """Test user orders list"""
        api_client.headers.update({"Authorization": f"Bearer {user_token}"})
        response = api_client.get(f"{BASE_URL}/api/user/orders")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ User orders API works: {len(data)} orders")

    def test_user_invoices_list(self, api_client, user_token):
        """Test user invoices list"""
        api_client.headers.update({"Authorization": f"Bearer {user_token}"})
        response = api_client.get(f"{BASE_URL}/api/user/invoices")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ User invoices API works: {len(data)} invoices")

    def test_user_shipments_list(self, api_client, user_token):
        """Test user shipments list"""
        api_client.headers.update({"Authorization": f"Bearer {user_token}"})
        response = api_client.get(f"{BASE_URL}/api/user/shipments")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ User shipments API works: {len(data)} shipments")


class TestAdminAuth:
    """Test admin authentication"""

    def test_admin_login_valid(self, api_client):
        """Test admin login with valid credentials"""
        response = api_client.post(f"{BASE_URL}/api/auth/login", json={
            "username": "admin",
            "password": "queencity2024"
        })
        assert response.status_code == 200
        data = response.json()
        assert "token" in data
        assert data.get("role") == "admin"
        print(f"✓ Admin login works")

    def test_admin_login_invalid(self, api_client):
        """Test admin login with invalid credentials"""
        response = api_client.post(f"{BASE_URL}/api/auth/login", json={
            "username": "admin",
            "password": "wrongpassword"
        })
        assert response.status_code == 401
        print("✓ Invalid admin login rejected")


class TestAdminDashboard:
    """Test admin dashboard APIs"""

    def test_admin_dashboard_stats(self, api_client, admin_token):
        """Test admin dashboard stats (8 stat cards)"""
        api_client.headers.update({"Authorization": f"Bearer {admin_token}"})
        response = api_client.get(f"{BASE_URL}/api/dashboard/stats")
        assert response.status_code == 200
        data = response.json()
        # Verify all stat fields for 8 stat cards
        assert "total_requests" in data
        assert "total_customers" in data
        assert "total_orders" in data
        assert "total_collected" in data
        assert "total_quotes" in data
        assert "unpaid_invoices" in data
        assert "paid_invoices" in data
        assert "total_profit" in data
        print(f"✓ Admin stats works: {data.get('total_requests')} requests, {data.get('total_customers')} customers")

    def test_admin_pipeline(self, api_client, admin_token):
        """Test admin pipeline view (9 stages)"""
        api_client.headers.update({"Authorization": f"Bearer {admin_token}"})
        response = api_client.get(f"{BASE_URL}/api/admin/pipeline")
        assert response.status_code == 200
        data = response.json()
        # Verify all 9 pipeline stages exist
        expected_stages = ["new_lead", "vin_review", "sourcing", "quote_sent", 
                          "invoice_sent", "paid", "ordered", "shipped", "delivered"]
        for stage in expected_stages:
            assert stage in data, f"Missing pipeline stage: {stage}"
        print(f"✓ Admin pipeline works: 9 stages found")

    def test_admin_customers_list(self, api_client, admin_token):
        """Test admin customers list"""
        api_client.headers.update({"Authorization": f"Bearer {admin_token}"})
        response = api_client.get(f"{BASE_URL}/api/admin/customers")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        if len(data) > 0:
            customer = data[0]
            assert "name" in customer
            assert "email" in customer
            assert "requests_count" in customer
        print(f"✓ Admin customers list works: {len(data)} customers")

    def test_admin_part_requests(self, api_client, admin_token):
        """Test admin part requests list"""
        api_client.headers.update({"Authorization": f"Bearer {admin_token}"})
        response = api_client.get(f"{BASE_URL}/api/part-requests")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ Admin requests works: {len(data)} requests")

    def test_admin_quotes_list(self, api_client, admin_token):
        """Test admin quotes list"""
        api_client.headers.update({"Authorization": f"Bearer {admin_token}"})
        response = api_client.get(f"{BASE_URL}/api/quotes")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ Admin quotes works: {len(data)} quotes")

    def test_admin_orders_list(self, api_client, admin_token):
        """Test admin orders list"""
        api_client.headers.update({"Authorization": f"Bearer {admin_token}"})
        response = api_client.get(f"{BASE_URL}/api/orders")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ Admin orders works: {len(data)} orders")

    def test_admin_invoices_list(self, api_client, admin_token):
        """Test admin invoices list"""
        api_client.headers.update({"Authorization": f"Bearer {admin_token}"})
        response = api_client.get(f"{BASE_URL}/api/invoices")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ Admin invoices works: {len(data)} invoices")

    def test_admin_shipments_list(self, api_client, admin_token):
        """Test admin shipments list"""
        api_client.headers.update({"Authorization": f"Bearer {admin_token}"})
        response = api_client.get(f"{BASE_URL}/api/shipments")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ Admin shipments works: {len(data)} shipments")

    def test_admin_contacts_list(self, api_client, admin_token):
        """Test admin contacts/leads list"""
        api_client.headers.update({"Authorization": f"Bearer {admin_token}"})
        response = api_client.get(f"{BASE_URL}/api/contacts")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ Admin contacts works: {len(data)} contacts")

    def test_admin_sourcing_notes(self, api_client, admin_token):
        """Test admin sourcing notes (Sourcing Hub)"""
        api_client.headers.update({"Authorization": f"Bearer {admin_token}"})
        response = api_client.get(f"{BASE_URL}/api/admin/sourcing-notes")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ Admin sourcing notes works: {len(data)} notes")


if __name__ == "__main__":
    pytest.main([__file__, "-v", "--tb=short"])
