# tests/integration/api/v1/platform/test_letzshop_vendors.py
"""Integration tests for platform Letzshop vendor lookup API endpoints.

Tests the /api/v1/platform/letzshop-vendors/* endpoints.
"""

import pytest

from app.modules.tenancy.models import Vendor
from app.modules.tenancy.models import Company


@pytest.fixture
def test_owner_user(db, auth_manager):
    """Create a test owner user for the company."""
    from app.modules.tenancy.models import User

    user = User(
        email="owner@test.com",
        username="test_owner",
        hashed_password=auth_manager.hash_password("testpass123"),
        role="vendor",
        is_active=True,
    )
    db.add(user)
    db.commit()
    return user


@pytest.fixture
def test_company(db, test_owner_user):
    """Create a test company."""
    company = Company(
        name="Test Company",
        owner_user_id=test_owner_user.id,
        contact_email="test@company.com",
    )
    db.add(company)
    db.commit()
    return company


@pytest.fixture
def claimed_vendor(db, test_company):
    """Create a vendor that has claimed a Letzshop shop."""
    vendor = Vendor(
        company_id=test_company.id,
        vendor_code="CLAIMED_VENDOR",
        subdomain="claimed-shop",
        name="Claimed Shop",
        contact_email="claimed@shop.lu",
        is_active=True,
        letzshop_vendor_slug="claimed-shop",
        letzshop_vendor_id="letz_123",
    )
    db.add(vendor)
    db.commit()
    return vendor


@pytest.mark.integration
@pytest.mark.api
@pytest.mark.platform
class TestLetzshopVendorLookupAPI:
    """Test Letzshop vendor lookup endpoints at /api/v1/platform/letzshop-vendors/*."""

    # =========================================================================
    # GET /api/v1/platform/letzshop-vendors
    # =========================================================================

    def test_list_vendors_returns_empty_list(self, client):
        """Test listing vendors returns empty list (placeholder)."""
        response = client.get("/api/v1/platform/letzshop-vendors")

        assert response.status_code == 200
        data = response.json()
        assert "vendors" in data
        assert "total" in data
        assert "page" in data
        assert "limit" in data
        assert "has_more" in data
        assert isinstance(data["vendors"], list)

    def test_list_vendors_with_pagination(self, client):
        """Test listing vendors with pagination parameters."""
        response = client.get("/api/v1/platform/letzshop-vendors?page=2&limit=10")

        assert response.status_code == 200
        data = response.json()
        assert data["page"] == 2
        assert data["limit"] == 10

    def test_list_vendors_with_search(self, client):
        """Test listing vendors with search parameter."""
        response = client.get("/api/v1/platform/letzshop-vendors?search=my-shop")

        assert response.status_code == 200
        data = response.json()
        assert isinstance(data["vendors"], list)

    def test_list_vendors_with_filters(self, client):
        """Test listing vendors with category and city filters."""
        response = client.get(
            "/api/v1/platform/letzshop-vendors?category=fashion&city=luxembourg"
        )

        assert response.status_code == 200
        data = response.json()
        assert isinstance(data["vendors"], list)

    def test_list_vendors_limit_validation(self, client):
        """Test that limit parameter is validated."""
        # Maximum limit is 50
        response = client.get("/api/v1/platform/letzshop-vendors?limit=100")
        assert response.status_code == 422

    # =========================================================================
    # POST /api/v1/platform/letzshop-vendors/lookup
    # =========================================================================

    def test_lookup_vendor_by_full_url(self, client):
        """Test looking up vendor by full Letzshop URL."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "https://letzshop.lu/vendors/my-test-shop"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["found"] is True
        assert data["vendor"]["slug"] == "my-test-shop"
        assert "letzshop.lu" in data["vendor"]["letzshop_url"]

    def test_lookup_vendor_by_url_with_language(self, client):
        """Test looking up vendor by URL with language prefix."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "https://letzshop.lu/en/vendors/my-shop"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["found"] is True
        assert data["vendor"]["slug"] == "my-shop"

    def test_lookup_vendor_by_url_without_protocol(self, client):
        """Test looking up vendor by URL without https://."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "letzshop.lu/vendors/test-shop"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["found"] is True
        assert data["vendor"]["slug"] == "test-shop"

    def test_lookup_vendor_by_slug_only(self, client):
        """Test looking up vendor by slug alone."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "my-shop-name"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["found"] is True
        assert data["vendor"]["slug"] == "my-shop-name"

    def test_lookup_vendor_normalizes_slug(self, client):
        """Test that slug is normalized to lowercase."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "https://letzshop.lu/vendors/MY-SHOP-NAME"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["vendor"]["slug"] == "my-shop-name"

    def test_lookup_vendor_shows_claimed_status(self, client, claimed_vendor):
        """Test that lookup shows if vendor is already claimed."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "claimed-shop"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["found"] is True
        assert data["vendor"]["is_claimed"] is True

    def test_lookup_vendor_shows_unclaimed_status(self, client):
        """Test that lookup shows if vendor is not claimed."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "unclaimed-new-shop"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["found"] is True
        assert data["vendor"]["is_claimed"] is False

    def test_lookup_vendor_empty_url(self, client):
        """Test lookup with empty URL."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": ""},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["found"] is False
        assert data["error"] is not None

    def test_lookup_vendor_response_has_expected_fields(self, client):
        """Test that vendor lookup response has all expected fields."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "test-vendor"},
        )

        assert response.status_code == 200
        data = response.json()
        vendor = data["vendor"]
        assert "slug" in vendor
        assert "name" in vendor
        assert "letzshop_url" in vendor
        assert "is_claimed" in vendor

    # =========================================================================
    # GET /api/v1/platform/letzshop-vendors/{slug}
    # =========================================================================

    def test_get_vendor_by_slug(self, client):
        """Test getting vendor by slug."""
        response = client.get("/api/v1/platform/letzshop-vendors/my-shop")

        assert response.status_code == 200
        data = response.json()
        assert data["slug"] == "my-shop"
        assert "name" in data
        assert "letzshop_url" in data
        assert "is_claimed" in data

    def test_get_vendor_normalizes_slug(self, client):
        """Test that get vendor normalizes slug to lowercase."""
        response = client.get("/api/v1/platform/letzshop-vendors/MY-SHOP")

        assert response.status_code == 200
        data = response.json()
        assert data["slug"] == "my-shop"

    def test_get_claimed_vendor_shows_status(self, client, claimed_vendor):
        """Test that get vendor shows claimed status correctly."""
        response = client.get("/api/v1/platform/letzshop-vendors/claimed-shop")

        assert response.status_code == 200
        data = response.json()
        assert data["is_claimed"] is True

    def test_get_unclaimed_vendor_shows_status(self, client):
        """Test that get vendor shows unclaimed status correctly."""
        response = client.get("/api/v1/platform/letzshop-vendors/new-unclaimed-shop")

        assert response.status_code == 200
        data = response.json()
        assert data["is_claimed"] is False


@pytest.mark.integration
@pytest.mark.api
@pytest.mark.platform
class TestLetzshopSlugExtraction:
    """Test slug extraction from various URL formats."""

    def test_extract_from_full_https_url(self, client):
        """Test extraction from https://letzshop.lu/vendors/slug."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "https://letzshop.lu/vendors/cafe-luxembourg"},
        )
        assert response.json()["vendor"]["slug"] == "cafe-luxembourg"

    def test_extract_from_http_url(self, client):
        """Test extraction from http://letzshop.lu/vendors/slug."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "http://letzshop.lu/vendors/my-shop"},
        )
        assert response.json()["vendor"]["slug"] == "my-shop"

    def test_extract_from_url_with_trailing_slash(self, client):
        """Test extraction from URL with trailing slash."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "https://letzshop.lu/vendors/my-shop/"},
        )
        assert response.json()["vendor"]["slug"] == "my-shop"

    def test_extract_from_url_with_query_params(self, client):
        """Test extraction from URL with query parameters."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "https://letzshop.lu/vendors/my-shop?ref=google"},
        )
        assert response.json()["vendor"]["slug"] == "my-shop"

    def test_extract_from_french_url(self, client):
        """Test extraction from French language URL."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "https://letzshop.lu/fr/vendors/boulangerie-paul"},
        )
        assert response.json()["vendor"]["slug"] == "boulangerie-paul"

    def test_extract_from_german_url(self, client):
        """Test extraction from German language URL."""
        response = client.post(
            "/api/v1/platform/letzshop-vendors/lookup",
            json={"url": "https://letzshop.lu/de/vendors/backerei-muller"},
        )
        assert response.json()["vendor"]["slug"] == "backerei-muller"
