import httpx
import respx

from whatsrb_cloud import WhatsrbCloud
from whatsrb_cloud.objects.webhook import Webhook
from whatsrb_cloud.objects.list_response import ListResponse

BASE_URL = "https://whatsrb.com/api/v1"

WEBHOOK_DATA = {
    "id": "wh_1",
    "url": "https://example.com/webhook",
    "events": ["message.received", "agent_run.completed"],
    "active": True,
    "secret": "whsec_xxx",
    "created_at": "2025-01-01T00:00:00Z",
    "updated_at": "2025-01-01T00:00:00Z",
}


class TestWebhooksResource:
    @respx.mock
    def test_list(self):
        respx.get(f"{BASE_URL}/webhooks").mock(
            return_value=httpx.Response(200, json={"data": [WEBHOOK_DATA], "meta": {}})
        )
        client = WhatsrbCloud("wrb_test")
        result = client.webhooks.list()
        assert isinstance(result, ListResponse)
        assert len(result) == 1
        assert result[0].url == "https://example.com/webhook"

    @respx.mock
    def test_create(self):
        respx.post(f"{BASE_URL}/webhooks").mock(
            return_value=httpx.Response(201, json={"data": WEBHOOK_DATA})
        )
        client = WhatsrbCloud("wrb_test")
        webhook = client.webhooks.create(url="https://example.com/webhook", events=["message.received"])
        assert isinstance(webhook, Webhook)
        assert webhook.secret == "whsec_xxx"

    @respx.mock
    def test_retrieve(self):
        no_secret = {**WEBHOOK_DATA}
        del no_secret["secret"]
        respx.get(f"{BASE_URL}/webhooks/wh_1").mock(
            return_value=httpx.Response(200, json={"data": no_secret})
        )
        client = WhatsrbCloud("wrb_test")
        webhook = client.webhooks.retrieve("wh_1")
        assert webhook.id == "wh_1"
        assert webhook.is_active is True
        assert webhook.secret is None

    @respx.mock
    def test_update(self):
        updated = {**WEBHOOK_DATA, "events": ["message.received"]}
        respx.patch(f"{BASE_URL}/webhooks/wh_1").mock(
            return_value=httpx.Response(200, json={"data": updated})
        )
        client = WhatsrbCloud("wrb_test")
        webhook = client.webhooks.update("wh_1", events=["message.received"])
        assert webhook.events == ["message.received"]

    @respx.mock
    def test_delete(self):
        respx.delete(f"{BASE_URL}/webhooks/wh_1").mock(
            return_value=httpx.Response(204, text="")
        )
        client = WhatsrbCloud("wrb_test")
        assert client.webhooks.delete("wh_1") is True

    @respx.mock
    def test_webhook_to_dict(self):
        respx.get(f"{BASE_URL}/webhooks/wh_1").mock(
            return_value=httpx.Response(200, json={"data": WEBHOOK_DATA})
        )
        client = WhatsrbCloud("wrb_test")
        webhook = client.webhooks.retrieve("wh_1")
        d = webhook.to_dict()
        assert d["id"] == "wh_1"
        assert d["url"] == "https://example.com/webhook"
