"""HTTP tests for GET /api/widget/autocomplete.

Autocomplete is a public read endpoint reached on every keystroke.
Tests cover query length floor, key validation, and that the JSON
shape matches what the widget's SSR row template expects (name,
company_name, city, url).
"""

from odoo.tests import tagged

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


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

    def _autocomplete(self, q="", key=None):
        params = {"key": key or self.config.widget_key, "q": q}
        url = "/api/widget/autocomplete?" + "&".join(
            f"{k}={v}" for k, v in params.items()
        )
        return self.url_open(url)

    def test_short_query_returns_empty(self):
        r = self._autocomplete(q="x")
        self.assertEqual(r.status_code, 200)
        body = r.json()
        # The widget JS only renders if results exist; empty list is OK.
        self.assertIsInstance(body.get("results"), list)

    def test_empty_query_returns_empty_or_no_results(self):
        r = self._autocomplete(q="")
        self.assertEqual(r.status_code, 200)
        body = r.json()
        self.assertEqual(body.get("results", []), [])

    def test_returns_shape_widget_renderer_expects(self):
        """Pin the response shape — `_wireOneAutocomplete` in kj_widget.js
        reads `name`, `company_name`, `city`, `url` on each result."""
        # Seed: a job with a deterministic name we can search for.
        self.env["hr.job"].create({
            "name": "Widget Autocomplete Marker Job",
            "company_id": self.company.id,
            "is_published": True,
            "active": True,
        })
        r = self._autocomplete(q="Marker")
        self.assertEqual(r.status_code, 200)
        results = r.json().get("results", [])
        self.assertTrue(results, "autocomplete returned no matches for seeded job")
        first = results[0]
        for k in ("name", "url"):
            self.assertIn(k, first, f"missing key {k!r} in autocomplete result")
        # `company_name` and `city` may be empty strings but the keys
        # should still exist so the widget JS doesn't have to defensive-check.
        # (Widget JS reads with `s.company_name || ""` so this is soft.)

    def test_invalid_key_returns_error(self):
        r = self._autocomplete(q="jur", key="not-real")
        # Endpoint may return 403 or empty results — both are acceptable;
        # we just don't want a 500.
        self.assertNotEqual(r.status_code, 500)
