"""Plugin table-ownership tests.

Bundled plugin schema is owned by the core migration chain (deploys run
`flask db upgrade` only, which reproduces the full schema). The per-plugin
Alembic helpers remain for external/filesystem plugins; these tests pin the
PLUGIN_TABLE_OWNERS registry those helpers consume.
"""
import pytest

from shopdb.plugins.alembic_template import (
    PLUGIN_TABLE_OWNERS,
    _get_plugin_metadata,
)


BUNDLED_PLUGINS = ('computers', 'equipment', 'network', 'notifications', 'printers', 'usb')


@pytest.mark.parametrize('plugin', BUNDLED_PLUGINS)
def test_bundled_plugin_has_table_owner_entry(plugin):
    """Every bundled plugin appears in PLUGIN_TABLE_OWNERS with at least
    one table, documenting which tables it contributes to the schema."""
    assert plugin in PLUGIN_TABLE_OWNERS
    assert len(PLUGIN_TABLE_OWNERS[plugin]) > 0


@pytest.mark.parametrize('plugin', BUNDLED_PLUGINS)
def test_plugin_metadata_has_all_owned_tables(plugin, app):
    """The MetaData filtered to a plugin's owned tables actually contains
    every table named in PLUGIN_TABLE_OWNERS. Catches drift between the
    registry and what the models declare."""
    with app.app_context():
        md = _get_plugin_metadata(plugin)
        owned = set(PLUGIN_TABLE_OWNERS[plugin])
        present = set(md.tables.keys())
        missing = owned - present
        assert not missing, f"Plugin {plugin}: tables in PLUGIN_TABLE_OWNERS not in metadata: {missing}"
