"""
Tests API webhooks.
"""

import pytest
from fastapi import HTTPException
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from pricewatch.app.api.main import (
    create_webhook,
    delete_webhook,
    list_webhooks,
    send_webhook_test,
    update_webhook,
)
from pricewatch.app.api.schemas import WebhookCreate, WebhookUpdate
from pricewatch.app.db.models import Base


def _make_session():
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
    session = sessionmaker(bind=engine)()
    return engine, session


def test_webhook_crud_and_test(monkeypatch):
    engine, session = _make_session()
    try:
        payload = WebhookCreate(event="price_changed", url="https://example.com/webhook")
        created = create_webhook(payload, session=session)
        assert created.id > 0

        items = list_webhooks(session=session)
        assert len(items) == 1

        updated = update_webhook(created.id, WebhookUpdate(enabled=False), session=session)
        assert updated.enabled is False

        with pytest.raises(HTTPException) as excinfo:
            send_webhook_test(created.id, session=session)
        assert excinfo.value.status_code == 409

        update_webhook(created.id, WebhookUpdate(enabled=True), session=session)

        called = {}

        def fake_post(url, json, headers, timeout):
            called["url"] = url
            called["json"] = json
            called["headers"] = headers
            called["timeout"] = timeout

            class FakeResponse:
                status_code = 200

                def raise_for_status(self):
                    return None

            return FakeResponse()

        monkeypatch.setattr("pricewatch.app.api.main.httpx.post", fake_post)
        response = send_webhook_test(created.id, session=session)
        assert response.status == "sent"
        assert called["json"]["event"] == "test"

        delete_webhook(created.id, session=session)
        assert list_webhooks(session=session) == []
    finally:
        session.close()
        engine.dispose()
