# tests/integration/api/v1/test_filtering.py
import pytest

from models.database.marketplace_product import MarketplaceProduct


@pytest.mark.integration
@pytest.mark.api
@pytest.mark.products
@pytest.mark.marketplace
class TestFiltering:
    def test_product_brand_filter_success(self, client, auth_headers, db):
        """Test filtering products by brand successfully"""
        # Create products with different brands using unique IDs
        import uuid

        unique_suffix = str(uuid.uuid4())[:8]

        products = [
            MarketplaceProduct(
                marketplace_product_id=f"BRAND1_{unique_suffix}",
                title="MarketplaceProduct 1",
                brand="BrandA",
            ),
            MarketplaceProduct(
                marketplace_product_id=f"BRAND2_{unique_suffix}",
                title="MarketplaceProduct 2",
                brand="BrandB",
            ),
            MarketplaceProduct(
                marketplace_product_id=f"BRAND3_{unique_suffix}",
                title="MarketplaceProduct 3",
                brand="BrandA",
            ),
        ]

        db.add_all(products)
        db.commit()

        # Filter by BrandA
        response = client.get(
            "/api/v1/marketplace/product?brand=BrandA", headers=auth_headers
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] >= 2  # At least our test products

        # Verify all returned products have BrandA
        for product in data["products"]:
            if product["marketplace_product_id"].endswith(unique_suffix):
                assert product["brand"] == "BrandA"

        # Filter by BrandB
        response = client.get(
            "/api/v1/marketplace/product?brand=BrandB", headers=auth_headers
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] >= 1  # At least our test product

    def test_product_marketplace_filter_success(self, client, auth_headers, db):
        """Test filtering products by marketplace successfully"""
        import uuid

        unique_suffix = str(uuid.uuid4())[:8]

        products = [
            MarketplaceProduct(
                marketplace_product_id=f"MKT1_{unique_suffix}",
                title="MarketplaceProduct 1",
                marketplace="Amazon",
            ),
            MarketplaceProduct(
                marketplace_product_id=f"MKT2_{unique_suffix}",
                title="MarketplaceProduct 2",
                marketplace="eBay",
            ),
            MarketplaceProduct(
                marketplace_product_id=f"MKT3_{unique_suffix}",
                title="MarketplaceProduct 3",
                marketplace="Amazon",
            ),
        ]

        db.add_all(products)
        db.commit()

        response = client.get(
            "/api/v1/marketplace/product?marketplace=Amazon", headers=auth_headers
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] >= 2  # At least our test products

        # Verify all returned products have Amazon marketplace
        amazon_products = [
            p
            for p in data["products"]
            if p["marketplace_product_id"].endswith(unique_suffix)
        ]
        for product in amazon_products:
            assert product["marketplace"] == "Amazon"

    def test_product_search_filter_success(self, client, auth_headers, db):
        """Test searching products by text successfully"""
        import uuid

        unique_suffix = str(uuid.uuid4())[:8]

        products = [
            MarketplaceProduct(
                marketplace_product_id=f"SEARCH1_{unique_suffix}",
                title=f"Apple iPhone {unique_suffix}",
                description="Smartphone",
            ),
            MarketplaceProduct(
                marketplace_product_id=f"SEARCH2_{unique_suffix}",
                title=f"Samsung Galaxy {unique_suffix}",
                description="Android phone",
            ),
            MarketplaceProduct(
                marketplace_product_id=f"SEARCH3_{unique_suffix}",
                title=f"iPad Tablet {unique_suffix}",
                description="Apple tablet",
            ),
        ]

        db.add_all(products)
        db.commit()

        # Search for "Apple"
        response = client.get(
            "/api/v1/marketplace/product?search=Apple", headers=auth_headers
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] >= 2  # iPhone and iPad

        # Search for "phone"
        response = client.get(
            "/api/v1/marketplace/product?search=phone", headers=auth_headers
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] >= 2  # iPhone and Galaxy

    def test_combined_filters_success(self, client, auth_headers, db):
        """Test combining multiple filters successfully"""
        import uuid

        unique_suffix = str(uuid.uuid4())[:8]

        products = [
            MarketplaceProduct(
                marketplace_product_id=f"COMBO1_{unique_suffix}",
                title=f"Apple iPhone {unique_suffix}",
                brand="Apple",
                marketplace="Amazon",
            ),
            MarketplaceProduct(
                marketplace_product_id=f"COMBO2_{unique_suffix}",
                title=f"Apple iPad {unique_suffix}",
                brand="Apple",
                marketplace="eBay",
            ),
            MarketplaceProduct(
                marketplace_product_id=f"COMBO3_{unique_suffix}",
                title=f"Samsung Phone {unique_suffix}",
                brand="Samsung",
                marketplace="Amazon",
            ),
        ]

        db.add_all(products)
        db.commit()

        # Filter by brand AND marketplace
        response = client.get(
            "/api/v1/marketplace/product?brand=Apple&marketplace=Amazon",
            headers=auth_headers,
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] >= 1  # At least iPhone matches both

        # Find our specific test product
        matching_products = [
            p
            for p in data["products"]
            if p["marketplace_product_id"].endswith(unique_suffix)
        ]
        for product in matching_products:
            assert product["brand"] == "Apple"
            assert product["marketplace"] == "Amazon"

    def test_filter_with_no_results(self, client, auth_headers):
        """Test filtering with criteria that returns no results"""
        response = client.get(
            "/api/v1/marketplace/product?brand=NonexistentBrand123456",
            headers=auth_headers,
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 0
        assert data["products"] == []

    def test_filter_case_insensitive(self, client, auth_headers, db):
        """Test that filters are case-insensitive"""
        import uuid

        unique_suffix = str(uuid.uuid4())[:8]

        product = MarketplaceProduct(
            marketplace_product_id=f"CASE_{unique_suffix}",
            title="Test MarketplaceProduct",
            brand="TestBrand",
            marketplace="TestMarket",
        )
        db.add(product)
        db.commit()

        # Test different case variations
        for brand_filter in ["TestBrand", "testbrand", "TESTBRAND"]:
            response = client.get(
                f"/api/v1/marketplace/product?brand={brand_filter}",
                headers=auth_headers,
            )
            assert response.status_code == 200
            data = response.json()
            assert data["total"] >= 1

    def test_invalid_filter_parameters(self, client, auth_headers):
        """Test behavior with invalid filter parameters"""
        # Test with very long filter values
        long_brand = "A" * 1000
        response = client.get(
            f"/api/v1/marketplace/product?brand={long_brand}", headers=auth_headers
        )
        assert response.status_code == 200  # Should handle gracefully

        # Test with special characters
        response = client.get(
            "/api/v1/marketplace/product?brand=<script>alert('test')</script>",
            headers=auth_headers,
        )
        assert response.status_code == 200  # Should handle gracefully
