"""Tests for Organizations client."""

import pytest
from pytest_httpx import HTTPXMock

from concentriq import ConcentriqClient
from concentriq.auth import ApiKeyAuth


class TestOrganizationsList:
    """Tests for Organizations.list() behavior."""

    def test_list_returns_list_of_organizations(self, httpx_mock: HTTPXMock):
        """List should return a list of organization data."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/organizations",
            json={
                "meta": {"status": 200},
                "data": {
                    "organizations": [
                        {"id": 1, "name": "Acme Corp", "billingEmail": "billing@acme.com"},
                        {"id": 2, "name": "Beta Inc", "billingEmail": "billing@beta.com"},
                    ]
                },
            },
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.organizations.list()

        assert isinstance(result, list)
        assert len(result) == 2
        assert result[0]["id"] == 1
        assert result[1]["name"] == "Beta Inc"

    def test_list_returns_empty_list_when_no_results(self, httpx_mock: HTTPXMock):
        """List should return empty list when API returns no data."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/organizations",
            json={"meta": {"status": 200}, "data": {"organizations": []}},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.organizations.list()

        assert result == []

    def test_list_raises_authentication_error_when_unauthorized(
        self, httpx_mock: HTTPXMock
    ):
        """List should raise AuthenticationError when API returns 401."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/organizations",
            status_code=401,
            json={"error": "Unauthorized"},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )

        from concentriq.exceptions import AuthenticationError

        with pytest.raises(AuthenticationError):
            client.v1.organizations.list()


class TestOrganizationsGet:
    """Tests for Organizations.get() behavior."""

    def test_get_returns_single_organization(self, httpx_mock: HTTPXMock):
        """Get should return a single organization by ID."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/organizations/123",
            json={
                "meta": {"status": 200},
                "data": {
                    "organization": {
                        "id": 123,
                        "name": "Test Org",
                        "billingEmail": "billing@test.com",
                    }
                },
            },
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.organizations.get(123)

        assert result["id"] == 123
        assert result["name"] == "Test Org"
        assert result["billingEmail"] == "billing@test.com"

    def test_get_raises_not_found_for_invalid_id(self, httpx_mock: HTTPXMock):
        """Get should raise NotFoundError for non-existent organization."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/organizations/99999",
            status_code=404,
            json={"error": "Organization not found"},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )

        from concentriq.exceptions import NotFoundError

        with pytest.raises(NotFoundError):
            client.v1.organizations.get(99999)


class TestOrganizationsCreate:
    """Tests for Organizations.create() behavior."""

    def test_create_returns_created_organization(self, httpx_mock: HTTPXMock):
        """Create should return the newly created organization data."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/organizations",
            method="POST",
            json={
                "meta": {"status": 200},
                "data": {
                    "id": 456,
                    "name": "New Organization",
                    "billingEmail": "billing@neworg.com",
                },
            },
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.organizations.create(
            {"name": "New Organization", "billingEmail": "billing@neworg.com"}
        )

        assert result["id"] == 456
        assert result["name"] == "New Organization"

    def test_create_raises_validation_error_on_invalid_data(
        self, httpx_mock: HTTPXMock
    ):
        """Create should raise ValidationError when data is invalid."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/organizations",
            method="POST",
            status_code=400,
            json={"error": "name is required"},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )

        from concentriq.exceptions import ValidationError

        with pytest.raises(ValidationError):
            client.v1.organizations.create({})

    def test_create_raises_authentication_error_when_unauthorized(
        self, httpx_mock: HTTPXMock
    ):
        """Create should raise AuthenticationError when not authenticated."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/organizations",
            method="POST",
            status_code=401,
            json={"error": "Unauthorized"},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )

        from concentriq.exceptions import AuthenticationError

        with pytest.raises(AuthenticationError):
            client.v1.organizations.create({"name": "Test"})
