"""Per-plugin Alembic chain wiring tests.

Pins the bundled-plugin migration setup so a future refactor that breaks
the scaffolding fails fast with a clear test rather than a confusing
runtime error on a fresh deploy.
"""
from pathlib import Path

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; otherwise its baseline migration would be a no-op."""
    assert plugin in PLUGIN_TABLE_OWNERS
    assert len(PLUGIN_TABLE_OWNERS[plugin]) > 0


@pytest.mark.parametrize('plugin', BUNDLED_PLUGINS)
def test_bundled_plugin_has_migrations_dir(plugin):
    """Each bundled plugin has the on-disk Alembic scaffolding."""
    root = Path(__file__).resolve().parent.parent / 'plugins' / plugin / 'migrations'
    assert (root / 'env.py').is_file(), f"{plugin}/migrations/env.py missing"
    assert (root / 'alembic.ini').is_file(), f"{plugin}/migrations/alembic.ini missing"
    assert (root / 'script.py.mako').is_file(), f"{plugin}/migrations/script.py.mako missing"
    versions = root / 'versions'
    assert versions.is_dir(), f"{plugin}/migrations/versions missing"
    baseline = versions / '0001_baseline.py'
    assert baseline.is_file(), f"{plugin}/migrations/versions/0001_baseline.py missing"


@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
    template's table list 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}"
