import importlib.util
from pathlib import Path

import pytest


ROOT = Path(__file__).resolve().parents[2]
SCRIPT_PATH = ROOT / "migrate_odoo.py"


def load_migration_module():
    spec = importlib.util.spec_from_file_location("migrate_odoo_for_test", SCRIPT_PATH)
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)
    return module


def test_migration_requires_target_tenant_before_querying_odoo(monkeypatch):
    module = load_migration_module()
    monkeypatch.delenv("ERP_TENANT_ID", raising=False)
    monkeypatch.setattr(
        module,
        "query_odoo",
        lambda _sql: (_ for _ in ()).throw(AssertionError("queried Odoo before validating tenant")),
    )

    with pytest.raises(RuntimeError, match="ERP_TENANT_ID"):
        module.main()


def test_all_tenant_owned_inserts_include_target_tenant_id():
    source = SCRIPT_PATH.read_text(encoding="utf-8")

    for table in (
        "customers",
        "customer_contacts",
        "products",
        "invoices",
        "invoice_items",
        "payments",
    ):
        assert f'INSERT INTO `{table}` (`id`, `tenant_id`' in source

