from unittest.mock import patch

from django.test import TestCase
from django.urls import reverse

from core.models import User


class SignalRelinkTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_superuser(
            username="signal-admin",
            email="signal-admin@example.com",
            password="x",
        )
        self.client.force_login(self.user)

    @patch("core.views.signal.transport.list_accounts")
    def test_signal_accounts_view_shows_relink_action(self, mock_list_accounts):
        mock_list_accounts.return_value = ["+447000000001"]
        response = self.client.get(reverse("signal_accounts", kwargs={"type": "page"}))
        self.assertEqual(200, response.status_code)
        self.assertContains(response, "Relink")
        self.assertContains(response, "/services/signal/")
        self.assertContains(response, "/unlink/+447000000001/")

    @patch("core.views.signal.transport.list_accounts")
    @patch("core.views.signal.transport.unlink_account")
    def test_signal_account_unlink_calls_transport_and_renders_panel(
        self,
        mock_unlink_account,
        mock_list_accounts,
    ):
        mock_list_accounts.side_effect = [
            ["+447000000001"],
            [],
        ]
        response = self.client.post(
            reverse(
                "signal_account_unlink",
                kwargs={"type": "page", "account": "+447000000001"},
            )
        )
        self.assertEqual(200, response.status_code)
        mock_unlink_account.assert_called_once_with("signal", "+447000000001")

    @patch("core.views.signal.transport.get_link_qr")
    def test_signal_account_add_renders_notify_when_qr_fetch_fails(self, mock_get_link_qr):
        mock_get_link_qr.side_effect = RuntimeError("timeout")

        response = self.client.post(
            reverse(
                "signal_account_add",
                kwargs={"type": "modal"},
            ),
            {"device": "My Device"},
            HTTP_HX_REQUEST="true",
            HTTP_HX_TARGET="modals-here",
        )

        self.assertEqual(200, response.status_code)
        self.assertContains(response, "modal is-active")
        self.assertContains(response, "Signal QR link is unavailable right now")
        self.assertContains(response, "timeout")
