"""Unit tests for optional Slack integration behavior."""

from __future__ import annotations

import unittest
from unittest.mock import Mock, patch

from kiessclaw.integrations.slack import SlackIntegration


class SlackIntegrationTest(unittest.TestCase):
    """Verify Slack notifications are non-fatal and well-formatted."""

    def test_notify_without_webhook_returns_false(self) -> None:
        """When webhook is missing, notify should no-op and return False."""
        slack = SlackIntegration(webhook_url=None, bot_token=None)
        self.assertFalse(slack.notify("qualified_lead", {"contact": "alex@acme.com", "icp_score": 75}))

    def test_format_lead_alert_contains_blocks(self) -> None:
        """Lead alert format should be valid Slack Block Kit payload."""
        slack = SlackIntegration(webhook_url="https://hooks.slack.com/services/test", bot_token=None)
        payload = slack.format_lead_alert("alex@acme.com", 72, "outreach_sdr")
        self.assertIn("blocks", payload)
        self.assertTrue(isinstance(payload["blocks"], list))

    def test_format_reply_alert_contains_blocks(self) -> None:
        """Reply alert format should include blocks key."""
        slack = SlackIntegration(webhook_url="https://hooks.slack.com/services/test", bot_token=None)
        payload = slack.format_reply_alert("alex@acme.com", "interested", "This looks good.")
        self.assertIn("blocks", payload)
        self.assertTrue(isinstance(payload["blocks"], list))

    @patch("kiessclaw.integrations.slack.requests.post")
    def test_notify_returns_true_on_http_200(self, post_mock: Mock) -> None:
        """HTTP 200 from webhook should return True."""
        post_mock.return_value = Mock(status_code=200)
        slack = SlackIntegration(webhook_url="https://hooks.slack.com/services/test", bot_token=None)
        self.assertTrue(slack.notify("workflow_complete", {"usecase_id": "outreach_sdr", "errors": []}))

    @patch("kiessclaw.integrations.slack.requests.post", side_effect=RuntimeError("network error"))
    def test_notify_exception_returns_false(self, _: Mock) -> None:
        """Webhook exceptions must be swallowed and return False."""
        slack = SlackIntegration(webhook_url="https://hooks.slack.com/services/test", bot_token=None)
        self.assertFalse(slack.notify("error", {"message": "x"}))


if __name__ == "__main__":
    unittest.main()
