"""Per-domain global-search toggles (search_<type>_enabled).

A content type can be hidden from search independently of whether its plugin is
enabled, by setting search_<type>_enabled = false.
"""

from shopdb.core.api.settings import SEARCH_DOMAINS


def _kb_types(client, auth_headers, term):
    resp = client.get(f'/api/search?q={term}', headers=auth_headers)
    assert resp.status_code == 200, resp.get_json()
    return [r for r in resp.get_json()['data']['results']
            if r.get('type') == 'knowledgebase']


def test_domain_included_by_default(client, db, auth_headers):
    """With no toggle set, the knowledgebase domain appears in search."""
    client.post('/api/knowledgebase',
                json={'shortdescription': 'searchtoggle alpha',
                      'linkurl': 'https://kb.example/a'},
                headers=auth_headers)
    assert _kb_types(client, auth_headers, 'searchtoggle')


def test_disabled_domain_excluded(client, db, auth_headers):
    """search_knowledgebase_enabled=false hides KB results."""
    from shopdb.core.models import Setting
    client.post('/api/knowledgebase',
                json={'shortdescription': 'searchtoggle beta',
                      'linkurl': 'https://kb.example/b'},
                headers=auth_headers)
    Setting.set('search_knowledgebase_enabled', False, valuetype='boolean',
                category='search')
    assert _kb_types(client, auth_headers, 'searchtoggle') == []


def test_search_seed_creates_domain_keys(client, db, auth_headers):
    """Seeding produces one boolean setting per search domain."""
    resp = client.post('/api/settings/seed', headers=auth_headers)
    assert resp.status_code == 200
    from shopdb.core.models import Setting
    keys = {s.key for s in Setting.query.filter_by(category='search').all()}
    assert {f'search_{k}_enabled' for k in SEARCH_DOMAINS} <= keys
