"""Tests for dashboard defaults (visitor-IP -> business-unit resolution)."""

import pytest


@pytest.fixture
def businessunit(db):
    from shopdb.core.models import BusinessUnit
    bu = BusinessUnit(businessunit='Materials')
    db.session.add(bu)
    db.session.commit()
    return bu


def test_create_and_resolve_visitor_location(client, db, auth_headers, businessunit):
    """A mapped IP resolves to its business unit; explicit ipaddress param works."""
    created = client.post('/api/dashboarddefaults', json={
        'ipaddress': '10.20.30.40',
        'businessunitid': businessunit.businessunitid,
        'description': 'Materials lobby kiosk',
    }, headers=auth_headers)
    assert created.status_code == 201, created.get_json()

    resolved = client.get('/api/dashboarddefaults/visitor-location?ipaddress=10.20.30.40')
    assert resolved.status_code == 200
    data = resolved.get_json()['data']
    assert data['businessunitid'] == businessunit.businessunitid
    assert data['businessunit'] == 'Materials'


def test_unmapped_ip_resolves_to_null(client, db):
    """An unmapped IP returns a null business unit, not an error."""
    resolved = client.get('/api/dashboarddefaults/visitor-location?ipaddress=1.2.3.4')
    assert resolved.status_code == 200
    assert resolved.get_json()['data']['businessunitid'] is None


def test_duplicate_ip_rejected(client, db, auth_headers, businessunit):
    """Mapping the same IP twice is a conflict."""
    payload = {'ipaddress': '10.0.0.9', 'businessunitid': businessunit.businessunitid}
    first = client.post('/api/dashboarddefaults', json=payload, headers=auth_headers)
    assert first.status_code == 201
    dup = client.post('/api/dashboarddefaults', json=payload, headers=auth_headers)
    assert dup.status_code == 409
