"""
Tests for the Teams Webhook library.
"""

import json
import pytest
import requests
from unittest.mock import Mock, patch

from lib.rajang_pywebhook import TeamsWebhook, MessageStatus


class TestTeamsWebhook:
    """Test cases for TeamsWebhook class."""
    
    def test_init_with_single_webhook(self):
        """Test initialization with a single webhook URL."""
        webhook = TeamsWebhook(webhook_url="https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81")
        assert webhook._webhook_url == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
        assert webhook._success_webhook_url == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
        assert webhook._error_webhook_url == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
    
    def test_init_with_separate_webhooks(self):
        """Test initialization with separate success and error webhooks."""
        webhook = TeamsWebhook(
            success_webhook_url="https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81",
            error_webhook_url="https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"

        )
        assert webhook._webhook_url is None
        assert webhook._success_webhook_url == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
        assert webhook._error_webhook_url == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
    
    def test_init_without_webhooks_raises_error(self):
        """Test that initialization without webhooks raises ValueError."""
        with pytest.raises(ValueError):
            TeamsWebhook()
    
    def test_get_webhook_url_single(self):
        """Test getting webhook URL with single webhook configuration."""
        webhook = TeamsWebhook(webhook_url="https://example.com/webhook")
        assert webhook._get_webhook_url("Success") == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
        assert webhook._get_webhook_url("Error") == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
        assert webhook._get_webhook_url("Warning") == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
    
    def test_get_webhook_url_separate(self):
        """Test getting webhook URL with separate webhook configuration."""
        webhook = TeamsWebhook(
            success_webhook_url="https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81",
            error_webhook_url="https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
        )
        assert webhook._get_webhook_url("Success") == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
        assert webhook._get_webhook_url("Info") == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
        assert webhook._get_webhook_url("Error") == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
        assert webhook._get_webhook_url("Warning") == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
    
    @patch("py_lib_template.teams_webhook.requests.post")
    def test_send_success(self, mock_post):
        """Test sending a successful message."""
        mock_response = Mock()
        mock_response.status_code = 200
        mock_post.return_value = mock_response
        
        webhook = TeamsWebhook(webhook_url="https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81")
        result = webhook.send(
            title="Test",
            message="Test message",
            data_source="Test App",
            status="Success"
        )
        
        assert result is True
        mock_post.assert_called_once()
        args, kwargs = mock_post.call_args
        assert args[0] == "https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81"
        assert kwargs["headers"]["Content-Type"] == "application/json"
    
    @patch("py_lib_template.teams_webhook.requests.post")
    def test_send_with_error_response(self, mock_post):
        """Test sending when the server returns an error."""
        mock_post.side_effect = requests.exceptions.RequestException("Connection error")
        
        webhook = TeamsWebhook(webhook_url="https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81")
        result = webhook.send(
            title="Test",
            message="Test message",
            data_source="Test App",
            status="Error"
        )
        
        assert result is False
    
    @patch("py_lib_template.teams_webhook.requests.post")
    def test_send_with_custom_payload(self, mock_post):
        """Test sending with a custom payload."""
        mock_response = Mock()
        mock_response.status_code = 200
        mock_post.return_value = mock_response
        
        custom_payload = {
            "type": "message",
            "attachments": [
                {
                    "contentType": "application/vnd.microsoft.card.adaptive",
                    "content": {"type": "AdaptiveCard", "version": "1.2"}
                }
            ]
        }
        
        webhook = TeamsWebhook(webhook_url="https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81")
        result = webhook.send(
            title="Test",
            message="Test message",
            data_source="Test App",
            status="Success",
            payload=custom_payload
        )
        
        assert result is True
        args, kwargs = mock_post.call_args
        assert kwargs["json"] == custom_payload
    
    @patch("py_lib_template.teams_webhook.requests.post")
    def test_convenience_methods(self, mock_post):
        """Test convenience methods (send_success, send_error, etc.)."""
        mock_response = Mock()
        mock_response.status_code = 200
        mock_post.return_value = mock_response
        
        webhook = TeamsWebhook(webhook_url="https://rajangmalaysia.webhook.office.com/webhookb2/0c58ee4d-9719-44bf-b551-09b7f2eaa286@01e3abbf-efcb-429e-98e5-49c85071b8bc/IncomingWebhook/d73e4d40522a4b42881363877f64afc0/57fb60a9-a8e3-43a8-84b6-266c89a78efb/V2Icb58rQ72cQu6n2WMdrgLcD1OwFVAYk5k56Peqwz7g81")
        
        webhook.send_success("Success", "Message", "App")
        args, kwargs = mock_post.call_args
        assert "Success" in json.dumps(kwargs["json"])
        
        webhook.send_error("Error", "Message", "App")
        args, kwargs = mock_post.call_args
        assert "Error" in json.dumps(kwargs["json"])
        
        webhook.send_warning("Warning", "Message", "App")
        args, kwargs = mock_post.call_args
        assert "Warning" in json.dumps(kwargs["json"])
        
        webhook.send_info("Info", "Message", "App")
        args, kwargs = mock_post.call_args
        assert "Info" in json.dumps(kwargs["json"])


class TestFormatObjectToMarkdown:
    """Test cases for _format_object_to_markdown function."""
    
    def test_string_input(self):
        """Test formatting a string."""
        from lib.rajang_pywebhook.teams_webhook import _format_object_to_markdown
        result = _format_object_to_markdown("simple string")
        assert result == "simple string"
    
    def test_json_string_input(self):
        """Test formatting a JSON string."""
        from lib.rajang_pywebhook.teams_webhook import _format_object_to_markdown
        result = _format_object_to_markdown('{"key": "value"}')
        assert "**key** : value" in result
    
    def test_dict_input(self):
        """Test formatting a dictionary."""
        from lib.rajang_pywebhook.teams_webhook import _format_object_to_markdown
        result = _format_object_to_markdown({"name": "test", "count": 42})
        assert "**name** : test" in result
        assert "**count** : 42" in result
    
    def test_list_in_dict(self):
        """Test formatting a dictionary with list values."""
        from lib.rajang_pywebhook.teams_webhook import _format_object_to_markdown
        result = _format_object_to_markdown({"items": ["a", "b", "c"]})
        assert "**items**" in result
        assert "a" in result
        assert "b" in result


class TestCreateDefaultPayload:
    """Test cases for _create_default_payload function."""
    
    def test_basic_payload_structure(self):
        """Test the basic structure of the generated payload."""
        from lib.rajang_pywebhook.teams_webhook import _create_default_payload
        
        payload = _create_default_payload(
            title="Test Title",
            data_source="Test App",
            message="Test message",
            status="Success"
        )
        
        assert payload["type"] == "message"
        assert "attachments" in payload
        assert len(payload["attachments"]) == 1
        
        content = payload["attachments"][0]["content"]
        assert content["type"] == "AdaptiveCard"
        assert content["version"] == "1.2"
        assert "body" in content
    
    def test_payload_with_environment(self):
        """Test payload with environment specified."""
        from lib.rajang_pywebhook.teams_webhook import _create_default_payload
        
        payload = _create_default_payload(
            title="Test",
            data_source="App",
            message="Message",
            status="Success",
            environment="production"
        )
        
        body = payload["attachments"][0]["content"]["body"]
        server_block = next(b for b in body if "Server" in b.get("text", ""))
        assert "production" in server_block["text"]
    
    def test_payload_with_custom_fields(self):
        """Test payload with custom fields."""
        from lib.rajang_pywebhook.teams_webhook import _create_default_payload
        
        payload = _create_default_payload(
            title="Test",
            data_source="App",
            message="Message",
            status="Success",
            custom_fields={"Build": "123", "Branch": "main"}
        )
        
        body = payload["attachments"][0]["content"]["body"]
        texts = [b.get("text", "") for b in body]
        assert any("Build" in t for t in texts)
        assert any("Branch" in t for t in texts)


class TestMessageStatus:
    """Test cases for MessageStatus enum."""
    
    def test_status_values(self):
        """Test that MessageStatus has the expected values."""
        assert MessageStatus.SUCCESS == "Success"
        assert MessageStatus.ERROR == "Error"
        assert MessageStatus.WARNING == "Warning"
        assert MessageStatus.INFO == "Info"
