# tests/integration/api/v1/admin/test_vendors.py
"""Integration tests for admin vendor management endpoints.

Tests the /api/v1/admin/vendors/* endpoints.
"""

import pytest


@pytest.mark.integration
@pytest.mark.api
@pytest.mark.admin
class TestAdminVendorsAPI:
    """Test admin vendor management endpoints at /api/v1/admin/vendors/*."""

    def test_get_all_vendors_admin(self, client, admin_headers, test_vendor):
        """Test admin getting all vendors."""
        response = client.get("/api/v1/admin/vendors", headers=admin_headers)

        assert response.status_code == 200
        data = response.json()
        assert data["total"] >= 1
        assert len(data["vendors"]) >= 1

        # Check that test_vendor is in the response
        vendor_codes = [
            vendor["vendor_code"]
            for vendor in data["vendors"]
            if "vendor_code" in vendor
        ]
        assert test_vendor.vendor_code in vendor_codes

    def test_get_all_vendors_non_admin(self, client, auth_headers):
        """Test non-admin trying to access admin vendor endpoint."""
        response = client.get("/api/v1/admin/vendors", headers=auth_headers)

        assert response.status_code == 403
        data = response.json()
        assert data["error_code"] == "ADMIN_REQUIRED"

    def test_toggle_vendor_verification_admin(self, client, admin_headers, test_vendor):
        """Test admin setting vendor verification status."""
        response = client.put(
            f"/api/v1/admin/vendors/{test_vendor.id}/verification",
            headers=admin_headers,
            json={"is_verified": True},
        )

        assert response.status_code == 200
        data = response.json()
        assert "id" in data
        assert "vendor_code" in data
        assert "is_verified" in data

    def test_toggle_vendor_verification_not_found(self, client, admin_headers):
        """Test admin verifying non-existent vendor."""
        response = client.put(
            "/api/v1/admin/vendors/99999/verification",
            headers=admin_headers,
            json={"is_verified": True},
        )

        assert response.status_code == 404
        data = response.json()
        assert data["error_code"] == "VENDOR_NOT_FOUND"
        assert "99999" in data["message"]
        assert "not found" in data["message"]

    def test_toggle_vendor_status_admin(self, client, admin_headers, test_vendor):
        """Test admin setting vendor active status."""
        response = client.put(
            f"/api/v1/admin/vendors/{test_vendor.id}/status",
            headers=admin_headers,
            json={"is_active": False},
        )

        assert response.status_code == 200
        data = response.json()
        assert "id" in data
        assert "vendor_code" in data
        assert "is_active" in data

    def test_toggle_vendor_status_not_found(self, client, admin_headers):
        """Test admin toggling status for non-existent vendor."""
        response = client.put(
            "/api/v1/admin/vendors/99999/status",
            headers=admin_headers,
            json={"is_active": True},
        )

        assert response.status_code == 404
        data = response.json()
        assert data["error_code"] == "VENDOR_NOT_FOUND"

    def test_get_vendor_statistics(self, client, admin_headers):
        """Test admin getting vendor statistics."""
        response = client.get("/api/v1/admin/vendors/stats", headers=admin_headers)

        assert response.status_code == 200
        data = response.json()
        assert "total" in data
        assert "verified" in data
        assert "pending" in data
        assert "inactive" in data
        assert isinstance(data["total"], int)

    def test_admin_pagination_vendors(self, client, admin_headers, test_vendor):
        """Test vendor pagination works correctly."""
        response = client.get(
            "/api/v1/admin/vendors?skip=0&limit=1", headers=admin_headers
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] >= 1
        assert len(data["vendors"]) >= 0
        assert "skip" in data
        assert "limit" in data


@pytest.mark.integration
@pytest.mark.api
@pytest.mark.admin
class TestAdminVendorCreationAPI:
    """Test admin vendor creation endpoints with platform assignment."""

    def test_create_vendor_without_platforms(
        self, client, admin_headers, test_company
    ):
        """Test creating a vendor without platform assignments."""
        import uuid

        unique_id = str(uuid.uuid4())[:8]
        response = client.post(
            "/api/v1/admin/vendors",
            headers=admin_headers,
            json={
                "company_id": test_company.id,
                "vendor_code": f"NOPLAT_{unique_id}",
                "subdomain": f"noplat{unique_id}",
                "name": f"No Platform Vendor {unique_id}",
            },
        )

        assert response.status_code == 200
        data = response.json()
        assert data["vendor_code"] == f"NOPLAT_{unique_id}".upper()
        assert data["company_id"] == test_company.id

    def test_create_vendor_with_platforms(
        self, client, admin_headers, test_company, test_platform, another_platform
    ):
        """Test creating a vendor with platform assignments."""
        import uuid

        unique_id = str(uuid.uuid4())[:8]
        response = client.post(
            "/api/v1/admin/vendors",
            headers=admin_headers,
            json={
                "company_id": test_company.id,
                "vendor_code": f"WITHPLAT_{unique_id}",
                "subdomain": f"withplat{unique_id}",
                "name": f"With Platform Vendor {unique_id}",
                "platform_ids": [test_platform.id, another_platform.id],
            },
        )

        assert response.status_code == 200
        data = response.json()
        assert data["vendor_code"] == f"WITHPLAT_{unique_id}".upper()

    def test_create_vendor_duplicate_code_fails(
        self, client, admin_headers, test_company, test_vendor
    ):
        """Test creating a vendor with duplicate code fails."""
        response = client.post(
            "/api/v1/admin/vendors",
            headers=admin_headers,
            json={
                "company_id": test_company.id,
                "vendor_code": test_vendor.vendor_code,
                "subdomain": "uniquesubdomain123",
                "name": "Duplicate Code Vendor",
            },
        )

        assert response.status_code == 409  # Conflict
        data = response.json()
        assert data["error_code"] == "VENDOR_ALREADY_EXISTS"

    def test_create_vendor_non_admin_fails(
        self, client, auth_headers, test_company
    ):
        """Test non-admin cannot create vendors."""
        import uuid

        unique_id = str(uuid.uuid4())[:8]
        response = client.post(
            "/api/v1/admin/vendors",
            headers=auth_headers,
            json={
                "company_id": test_company.id,
                "vendor_code": f"NONADMIN_{unique_id}",
                "subdomain": f"nonadmin{unique_id}",
                "name": "Non Admin Vendor",
            },
        )

        assert response.status_code == 403
