"""Tests for the PR merged webhook handler."""

from unittest.mock import AsyncMock, patch

import pytest

from api.webhooks.pr_merged import handle_pr_merged


class TestPRMergedWebhook:
    """Test PR merged webhook handler."""

    @pytest.mark.asyncio
    async def test_no_event_found(self):
        """Should return ignored if no self-heal event found."""
        with patch("api.webhooks.pr_merged.get_self_heal_event_by_pr", return_value=None):
            result = await handle_pr_merged("https://github.com/test/repo/pull/999")

        assert result["action"] == "ignored"

    @pytest.mark.asyncio
    async def test_event_without_test_name(self):
        """Should return ignored if event has no test_name."""
        with patch("api.webhooks.pr_merged.get_self_heal_event_by_pr", return_value={
            "id": "evt_1",
            "test_name": None,
            "org_id": "org_1",
        }):
            result = await handle_pr_merged("https://github.com/test/repo/pull/1")

        assert result["action"] == "ignored"

    @pytest.mark.asyncio
    async def test_successful_unquarantine(self):
        """Should unquarantine test when PR is merged."""
        mock_event = {
            "id": "evt_1",
            "test_name": "test_flaky_one",
            "org_id": "org_1",
        }

        mock_manager = AsyncMock()

        with patch("api.webhooks.pr_merged.get_self_heal_event_by_pr", return_value=mock_event), \
             patch("api.webhooks.pr_merged.update_self_heal_event") as mock_update, \
             patch("api.webhooks.pr_merged.QuarantineManager", return_value=mock_manager):

            result = await handle_pr_merged(
                "https://github.com/test/repo/pull/1",
                merged_by="testuser",
            )

        assert result["action"] == "unquarantined"
        assert result["test_name"] == "test_flaky_one"
        mock_update.assert_called_once()
        mock_manager.unquarantine_test.assert_called_once_with("test_flaky_one")

    @pytest.mark.asyncio
    async def test_unquarantine_failure(self):
        """Should return partial if unquarantine fails."""
        mock_event = {
            "id": "evt_1",
            "test_name": "test_flaky_one",
            "org_id": "org_1",
        }

        with patch("api.webhooks.pr_merged.get_self_heal_event_by_pr", return_value=mock_event), \
             patch("api.webhooks.pr_merged.update_self_heal_event"), \
             patch("api.webhooks.pr_merged.QuarantineManager", side_effect=Exception("Connection failed")):

            result = await handle_pr_merged("https://github.com/test/repo/pull/1")

        assert result["action"] == "partial"
