from __future__ import annotations

import asyncio

from django.test import TestCase

from core.clients import transport
from core.clients.whatsapp import WhatsAppClient


class WhatsAppSendRoutingTests(TestCase):
    def setUp(self):
        self.loop = asyncio.new_event_loop()
        self.client = WhatsAppClient(ur=None, loop=self.loop)

    def tearDown(self):
        try:
            self.loop.close()
        except Exception:
            pass

    def test_to_jid_prefers_known_group_mapping(self):
        transport.update_runtime_state(
            "whatsapp",
            groups=[
                {
                    "identifier": "120363402761690215",
                    "jid": "120363402761690215@g.us",
                }
            ],
        )
        jid = self.client._to_jid("120363402761690215")
        self.assertEqual("120363402761690215@g.us", jid)

    def test_to_jid_keeps_phone_number_for_direct_chat(self):
        transport.update_runtime_state("whatsapp", groups=[])
        jid = self.client._to_jid("+14155551212")
        self.assertEqual("14155551212@s.whatsapp.net", jid)
