"""Regression: /api/reports/pc-relationships must return PC<->machine links
regardless of edge direction.

The import stores the general machinerelationships as machine(source) ->
PC(target); an earlier query only matched PC(source) -> machine(target), so on
prod (331 relationships) the report came back empty. The query is now
direction-agnostic.
"""


def _asset(db, assettype_name, plugin, table, assetnumber):
    from shopdb.core.models import AssetType, Asset
    at = AssetType.query.filter_by(assettype=assettype_name).first()
    if not at:
        at = AssetType(assettype=assettype_name, pluginname=plugin, tablename=table)
        db.session.add(at)
        db.session.flush()
    asset = Asset(assettypeid=at.assettypeid, assetnumber=assetnumber)
    db.session.add(asset)
    db.session.flush()
    return asset


def test_pc_relationships_matches_machine_to_pc_direction(client, db, auth_headers):
    from shopdb.core.models import AssetRelationship, RelationshipType
    from plugins.computers.models import Computer
    from plugins.machines.models import Machine

    pc_asset = _asset(db, 'computer', 'computers', 'computers', 'TESTPC01')
    eq_asset = _asset(db, 'machine', 'machines', 'machines', '4242')
    db.session.add(Computer(assetid=pc_asset.assetid, hostname='testpc01'))
    db.session.add(Machine(assetid=eq_asset.assetid))

    rt = RelationshipType.query.filter_by(relationshiptype='controls').first()
    if not rt:
        rt = RelationshipType(relationshiptype='controls')
        db.session.add(rt)
        db.session.flush()

    # REVERSE of the old-only direction: machine is the source, PC the target.
    db.session.add(AssetRelationship(
        sourceassetid=eq_asset.assetid, targetassetid=pc_asset.assetid,
        relationshiptypeid=rt.relationshiptypeid, isactive=True))
    db.session.commit()

    resp = client.get('/api/reports/pc-relationships', headers=auth_headers)
    assert resp.status_code == 200
    rows = resp.get_json()['data']['data']
    assert any(r['machine_number'] == '4242' and r['hostname'] == 'testpc01'
               for r in rows), rows
