from __future__ import annotations

import io
from urllib.error import HTTPError, URLError

import pytest


def test_post_to_slack_success_ok(monkeypatch):
    from backend.notifications import slack_sender

    class _Resp:
        def getcode(self):
            return 200

        def read(self):
            return b"ok"

    def fake_urlopen(req, timeout=None):
        return _Resp()

    monkeypatch.setattr(slack_sender, "urlopen", fake_urlopen)

    result = slack_sender.post_to_slack("https://example.invalid/webhook", {"blocks": []})
    assert result["success"] is True
    assert result["status_code"] == 200
    assert "successfully" in result["message"].lower()


def test_post_to_slack_http_error(monkeypatch):
    from backend.notifications import slack_sender

    def fake_urlopen(req, timeout=None):
        fp = io.BytesIO(b"invalid_payload")
        raise HTTPError(req.full_url, 400, "Bad Request", hdrs=None, fp=fp)

    monkeypatch.setattr(slack_sender, "urlopen", fake_urlopen)

    result = slack_sender.post_to_slack("https://example.invalid/webhook", {"blocks": []})
    assert result["success"] is False
    assert result["status_code"] == 400
    assert "HTTP 400" in result["message"]


def test_post_to_slack_url_error(monkeypatch):
    from backend.notifications import slack_sender

    def fake_urlopen(req, timeout=None):
        raise URLError("no route to host")

    monkeypatch.setattr(slack_sender, "urlopen", fake_urlopen)

    result = slack_sender.post_to_slack("https://example.invalid/webhook", {"blocks": []})
    assert result["success"] is False
    assert result["status_code"] is None
    assert "Connection error" in result["message"]


def test_send_test_message_payload_has_expected_header(monkeypatch):
    from backend.notifications import slack_sender

    captured = {}

    def fake_post_to_slack(webhook_url, payload):
        captured["webhook_url"] = webhook_url
        captured["payload"] = payload
        return {"success": True, "status_code": 200, "message": "ok"}

    monkeypatch.setattr(slack_sender, "post_to_slack", fake_post_to_slack)

    result = slack_sender.send_test_message("https://example.invalid/webhook")
    assert result["success"] is True
    payload = captured["payload"]
    assert "blocks" in payload and isinstance(payload["blocks"], list)
    header = payload["blocks"][0]
    assert header["type"] == "header"
    assert "Cascade Connected Successfully" in header["text"]["text"]

