"""Tests for the Relayway API client."""
from unittest.mock import Mock

import pytest

from relayway.client import RelayWayError, enqueue_job


def test_enqueue_job_posts_expected_payload(monkeypatch):
    response = Mock()
    response.status_code = 201
    response.json.return_value = {"id": "task-123", "status": "pending"}

    post_mock = Mock(return_value=response)

    monkeypatch.setattr("relayway.client.BASE_URL", "http://api.relayway.com")
    monkeypatch.setattr("relayway.client.API_KEY", "sk_test_key")
    monkeypatch.setattr("relayway.client.requests.post", post_mock)

    result = enqueue_job(
        payload={"to": "test@example.com"},
        origin="http://customer.com/webhook"
    )

    assert result == {"id": "task-123", "status": "pending"}
    post_mock.assert_called_once_with(
        "http://api.relayway.com/api/v1/tasks/create-task",
        json={
            "payload": {"to": "test@example.com"},
            "origin": "http://customer.com/webhook",
            "language": "python",
            "status": "pending",
        },
        headers={"Content-Type": "application/json", "X-API-Key": "sk_test_key"},
        timeout=10,
    )


def test_enqueue_job_works_without_api_key(monkeypatch):
    response = Mock()
    response.status_code = 201
    response.json.return_value = {"id": "task-123"}

    post_mock = Mock(return_value=response)

    monkeypatch.setattr("relayway.client.BASE_URL", "http://localhost:8000")
    monkeypatch.setattr("relayway.client.API_KEY", None)
    monkeypatch.setattr("relayway.client.requests.post", post_mock)

    enqueue_job(payload={}, origin="http://localhost/webhook")

    call_args = post_mock.call_args
    assert "X-API-Key" not in call_args.kwargs["headers"]


def test_enqueue_job_raises_on_non_serializable_payload(monkeypatch):
    monkeypatch.setattr("relayway.client.BASE_URL", "http://localhost:8000")
    monkeypatch.setattr("relayway.client.API_KEY", None)

    with pytest.raises(ValueError, match="JSON serializable"):
        enqueue_job(payload={"bad": object()}, origin="http://localhost/webhook")


def test_enqueue_job_raises_relayway_error_for_http_errors(monkeypatch):
    response = Mock()
    response.status_code = 500
    response.text = "Internal Server Error"

    monkeypatch.setattr("relayway.client.BASE_URL", "http://localhost:8000")
    monkeypatch.setattr("relayway.client.API_KEY", None)
    monkeypatch.setattr("relayway.client.requests.post", Mock(return_value=response))

    with pytest.raises(RelayWayError, match="500"):
        enqueue_job(payload={}, origin="http://localhost/webhook")
