"""Tests for the admin tooling on affiliate.widget.config.

Covers the embed-snippet field, the shareable preview page, and the
chatter auto-subscription of the affiliate partner.
"""

from odoo.tests import tagged

from odoo.addons.kj_affiliate_widget.tests.common import WidgetTestCommon


@tagged("post_install", "-at_install", "kj_affiliate_widget")
class TestWidgetAdminTools(WidgetTestCommon):

    def test_embed_code_computed(self):
        """embed_code holds the embed snippet with a script tag."""
        self.assertTrue(self.config.embed_code)
        self.assertIn("<script", self.config.embed_code)
        self.assertIn(self.config.widget_key, self.config.embed_code)

    def test_create_subscribes_affiliate_partner(self):
        """Creating a config subscribes the affiliate partner to the chatter."""
        self.assertIn(
            self.config.partner_id,
            self.config.message_follower_ids.partner_id,
            "the affiliate partner should be a chatter follower",
        )

    def test_preview_renders_for_valid_key(self):
        """The preview page is public, single-mode, and marked noindex."""
        r = self.url_open(
            "/api/widget/preview/%s?mode=%s"
            % (self.config.widget_key, self.config.widget_mode)
        )
        self.assertEqual(r.status_code, 200)
        self.assertIn("noindex", r.text)
        self.assertIn(
            'data-kj-mode="%s"' % self.config.widget_mode, r.text,
        )
        self.assertEqual(r.headers.get("X-Robots-Tag"), "noindex, nofollow")

    def test_preview_unknown_key_returns_404(self):
        r = self.url_open("/api/widget/preview/no-such-key-at-all")
        self.assertEqual(r.status_code, 404)

    def test_preview_action_url(self):
        """The header button returns a shareable act_url for this mode."""
        act = self.config.action_preview_widget()
        self.assertEqual(act["type"], "ir.actions.act_url")
        self.assertEqual(act["target"], "new")
        self.assertIn(
            "/api/widget/preview/%s" % self.config.widget_key, act["url"],
        )
        self.assertIn("mode=%s" % self.config.widget_mode, act["url"])
