"""Global search must exclude rows from disabled plugins (search.py _require_enabled).

Pins the data-exposure property: disabling a plugin removes its plugin-specific
matches (e.g. hostname) from /api/search, mirroring the plugin being absent.

Search by HOSTNAME (distinct from assetnumber) so only the gated hostname domain
can match - the core asset-number domain is intentionally always-on.
"""


def _seed_computer(client, db, auth_headers, assetnumber, hostname):
    from shopdb.core.models import AssetType
    if not AssetType.query.filter_by(assettype='computer').first():
        db.session.add(AssetType(assettype='computer', pluginname='computer',
                                 tablename='computer', description='c'))
        db.session.commit()
    resp = client.post('/api/computers',
                       json={'assetnumber': assetnumber, 'hostname': hostname},
                       headers=auth_headers)
    assert resp.status_code == 201, resp.get_json()


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


def test_search_includes_enabled_plugin(app, client, db, auth_headers, monkeypatch):
    """An enabled plugin's hostname matches appear in search."""
    _seed_computer(client, db, auth_headers, 'AST-SD01', 'hostsearch01')
    pm = app.extensions['plugin_manager']
    monkeypatch.setattr(pm.registry, 'is_enabled', lambda name: True)
    assert _computer_hits(client, auth_headers, 'hostsearch01')


def test_search_excludes_disabled_plugin(app, client, db, auth_headers, monkeypatch):
    """A disabled plugin's hostname matches drop out of search results."""
    _seed_computer(client, db, auth_headers, 'AST-SD02', 'hostsearch02')
    pm = app.extensions['plugin_manager']
    monkeypatch.setattr(pm.registry, 'is_enabled', lambda name: name != 'computers')
    assert _computer_hits(client, auth_headers, 'hostsearch02') == []
