"""Linked projects: migrations that depend on migrations from other projects.

All tests drive mitch through the CLI against SQLite files under tmp_path.
"""

import sqlite3
from pathlib import Path

from typer.testing import CliRunner

from mitch.cli import app

runner = CliRunner()


def make_project(
    path: Path,
    project_id: str,
    migrations: dict[str, dict] | None = None,
    links: dict[str, str] | None = None,
) -> Path:
    """Write a project directory.

    `migrations` maps a migration ID to a dict with optional keys `up`, `down` and `dependencies`.
    `links` maps an alias to a path relative to the project root.
    """
    path.mkdir(parents=True, exist_ok=True)
    lines = ["[project]", f'id = "{project_id}"']
    if links:
        lines.append("")
        lines.append("[projects]")
        lines.extend(f'"{alias}" = "{target}"' for alias, target in links.items())
    (path / "mitch.toml").write_text("\n".join(lines) + "\n", encoding="utf-8")

    for migration_id, spec in (migrations or {}).items():
        (path / f"{migration_id}.up.sql").write_text(spec.get("up", ""), encoding="utf-8")
        if "down" in spec:
            (path / f"{migration_id}.down.sql").write_text(spec["down"], encoding="utf-8")
        if spec.get("dependencies"):
            deps = ", ".join(f'"{d}"' for d in spec["dependencies"])
            (path / f"{migration_id}.config.toml").write_text(f"dependencies = [{deps}]\n", encoding="utf-8")
    return path


def table(name: str) -> dict:
    """Migration spec creating and dropping a table."""
    return {"up": f"CREATE TABLE {name} (id int);", "down": f"DROP TABLE {name};"}


def table_with(name: str, *dependencies: str) -> dict:
    return {**table(name), "dependencies": list(dependencies)}


def tables(db_path: Path) -> set[str]:
    with sqlite3.connect(db_path) as connection:
        rows = connection.execute("SELECT name FROM sqlite_schema WHERE type = 'table'").fetchall()
    return {row[0] for row in rows if not row[0].startswith("mitch_")}


def applied(db_path: Path) -> set[tuple[str, str]]:
    """(project ID, migration ID) pairs recorded as applied."""
    with sqlite3.connect(db_path) as connection:
        rows = connection.execute(
            "SELECT p.id, m.id FROM mitch_migrations m JOIN mitch_projects p ON p.local_id = m.project_id"
        ).fetchall()
    return {(row[0], row[1]) for row in rows}


def mitch(*args: str):
    return runner.invoke(app, list(args))


def test_up_applies_required_migration_of_nested_project_but_nothing_else(tmp_path):
    root = make_project(tmp_path / "app", "app", {"groups": table_with("groups", "users:create-users")})
    make_project(root / "users", "org.example.users", {"create-users": table("users"), "audit": table("audit")})
    db = tmp_path / "test.db"

    result = mitch("up", "-p", str(root), "-d", f"sqlite:///{db}")

    assert result.exit_code == 0, result.output
    assert tables(db) == {"users", "groups"}
    assert applied(db) == {("app", "groups"), ("org.example.users", "create-users")}


def db_url(tmp_path: Path) -> str:
    return f"sqlite:///{tmp_path / 'test.db'}"


def test_declared_link_to_sibling_directory(tmp_path):
    root = make_project(
        tmp_path / "app", "app", {"groups": table_with("groups", "um:create-users")}, links={"um": "../shared/users"}
    )
    make_project(tmp_path / "shared" / "users", "org.example.users", {"create-users": table("users")})

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == {"users", "groups"}


def test_declaration_overrides_alias_of_nested_project(tmp_path):
    root = make_project(
        tmp_path / "app", "app", {"groups": table_with("groups", "um:create-users")}, links={"um": "vendor/users"}
    )
    make_project(root / "vendor" / "users", "org.example.users", {"create-users": table("users")})

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == {"users", "groups"}


def test_two_nested_projects_with_the_same_directory_name_collide(tmp_path):
    root = make_project(tmp_path / "app", "app", {"groups": table("groups")})
    make_project(root / "a" / "users", "org.example.users")
    make_project(root / "b" / "users", "org.example.other-users")

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "Alias 'users'" in result.output


def test_declared_link_without_project_fails_with_alias_and_path(tmp_path):
    root = make_project(tmp_path / "app", "app", {"groups": table("groups")}, links={"um": "vendor/users"})
    (root / "vendor" / "users").mkdir(parents=True)

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "'um'" in result.output
    assert str(root / "vendor" / "users") in result.output


def test_status_only_warns_about_missing_linked_project(tmp_path):
    root = make_project(tmp_path / "app", "app", {"groups": table("groups")}, links={"um": "vendor/users"})

    result = mitch("status", "-p", str(root), "-d", db_url(tmp_path), "--no-ci")

    assert result.exit_code == 0, result.output
    assert "'um'" in result.output
    assert "A groups" in result.output


def test_alias_with_colon_is_rejected(tmp_path):
    root = make_project(tmp_path / "app", "app", {"groups": table("groups")}, links={"u:m": "../users"})
    make_project(tmp_path / "users", "org.example.users")

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "u:m" in result.output


def test_reference_to_transitively_linked_project_is_rejected(tmp_path):
    root = make_project(tmp_path / "app", "app", {"groups": table_with("groups", "utils:helpers")})
    users = make_project(root / "users", "org.example.users", {"create-users": table("users")})
    make_project(users / "utils", "org.example.utils", {"helpers": table("helpers")})

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "utils:helpers" in result.output
    assert tables(tmp_path / "test.db") == set()


def _diamond(tmp_path, utils_in_b: dict | None = None):
    """app links a and b; both link their own copy of utils under different aliases."""
    root = make_project(
        tmp_path / "app", "app", {"top": table_with("top", "a:in-a", "b:in-b")}, links={"a": "../a", "b": "../b"}
    )
    a = make_project(
        tmp_path / "a", "org.example.a", {"in-a": table_with("in_a", "u:helpers")}, links={"u": "vendor/utils"}
    )
    b = make_project(
        tmp_path / "b", "org.example.b", {"in-b": table_with("in_b", "tools:helpers")}, links={"tools": "vendor/utils"}
    )
    make_project(a / "vendor" / "utils", "org.example.utils", {"helpers": table("helpers")})
    make_project(b / "vendor" / "utils", "org.example.utils", utils_in_b or {"helpers": table("helpers")})
    return root


def test_diamond_applies_shared_project_once_under_its_project_id(tmp_path):
    root = _diamond(tmp_path)

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == {"top", "in_a", "in_b", "helpers"}
    assert ("org.example.utils", "helpers") in applied(tmp_path / "test.db")


def test_copies_with_different_content_for_the_same_migration_conflict(tmp_path):
    root = _diamond(tmp_path, utils_in_b={"helpers": {"up": "CREATE TABLE helpers (id int, name text);"}})

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "helpers" in result.output and "differs between copies" in result.output
    assert tables(tmp_path / "test.db") == set()


def test_copies_differing_only_in_formatting_or_set_of_migrations_are_merged(tmp_path):
    root = _diamond(
        tmp_path,
        utils_in_b={"helpers": {"up": "create table helpers (id int); -- same"}, "extra": table("extra")},
    )

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == {"top", "in_a", "in_b", "helpers"}


def test_links_may_form_a_cycle(tmp_path):
    root = make_project(tmp_path / "a", "org.example.a", {"in-a": table_with("in_a", "b:in-b")}, links={"b": "../b"})
    make_project(
        tmp_path / "b",
        "org.example.b",
        {"in-b": table("in_b"), "uses-a": table_with("uses_a", "a:in-a")},
        links={"a": "../a"},
    )

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == {"in_a", "in_b"}


def test_cycle_in_migration_graph_across_projects_is_an_error(tmp_path):
    root = make_project(tmp_path / "a", "org.example.a", {"in-a": table_with("in_a", "b:in-b")}, links={"b": "../b"})
    make_project(tmp_path / "b", "org.example.b", {"in-b": table_with("in_b", "a:in-a")}, links={"a": "../a"})

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "cycle" in result.output


def _app_with_users(tmp_path, app_migrations: dict | None = None) -> Path:
    root = make_project(
        tmp_path / "app",
        "app",
        app_migrations or {"groups": table_with("groups", "um:create-users"), "teams": table("teams")},
        links={"um": "../users"},
    )
    make_project(tmp_path / "users", "org.example.users", {"create-users": table("users"), "audit": table("audit")})
    return root


def _write_dependencies(project: Path, migration_id: str, *dependencies: str) -> None:
    deps = ", ".join(f'"{d}"' for d in dependencies)
    (project / f"{migration_id}.config.toml").write_text(f"dependencies = [{deps}]\n", encoding="utf-8")


def test_add_rejects_migrations_of_linked_projects(tmp_path):
    root = _app_with_users(tmp_path)

    result = mitch("add", "um:audit", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "um:audit" in result.output
    assert tables(tmp_path / "test.db") == set()


def test_drop_of_linked_migration_reverts_it_with_its_dependants(tmp_path):
    root = _app_with_users(tmp_path)
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    result = mitch("drop", "um:create-users", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == {"teams"}


def test_down_also_reverts_orphaned_linked_migrations(tmp_path):
    root = _app_with_users(tmp_path)
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    result = mitch("down", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == set()
    assert applied(tmp_path / "test.db") == set()


def test_drop_of_own_migration_reverts_linked_migration_it_alone_required(tmp_path):
    root = _app_with_users(tmp_path)
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    result = mitch("drop", "groups", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == {"teams"}


def test_down_keeps_linked_migration_another_project_on_the_deployment_still_needs(tmp_path):
    root = _app_with_users(tmp_path)
    other = make_project(
        tmp_path / "other",
        "org.example.other",
        {"profiles": table_with("profiles", "people:create-users")},
        links={"people": "../users"},
    )
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    mitch("up", "-p", str(other), "-d", db_url(tmp_path))

    result = mitch("down", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == {"users", "profiles"}

    result = mitch("down", "-p", str(other), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == set()


def test_revert_is_refused_while_a_project_that_is_not_loaded_depends_on_it(tmp_path):
    root = _app_with_users(tmp_path)
    other = make_project(
        tmp_path / "other",
        "org.example.other",
        {"profiles": table_with("profiles", "people:create-users")},
        links={"people": "../users"},
    )
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    mitch("up", "-p", str(other), "-d", db_url(tmp_path))

    result = mitch("drop", "um:create-users", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "org.example.other:profiles" in result.output
    assert tables(tmp_path / "test.db") == {"users", "groups", "teams", "profiles"}


def test_down_keeps_migrations_the_linked_project_applied_as_its_own(tmp_path):
    root = _app_with_users(tmp_path)
    mitch("up", "-p", str(tmp_path / "users"), "-d", db_url(tmp_path))
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    result = mitch("down", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == {"users", "audit"}


def test_removed_dependency_lets_the_next_revert_clean_up_the_linked_migration(tmp_path):
    root = _app_with_users(tmp_path)
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    (root / "groups.config.toml").unlink()

    result = mitch("drop", "teams", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == {"groups"}


def test_added_dependency_on_unapplied_migration_counts_as_modified(tmp_path):
    root = _app_with_users(tmp_path)
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    _write_dependencies(root, "teams", "um:audit")

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code != 0
    assert "teams" in result.output
    assert "audit" not in tables(tmp_path / "test.db")


def test_late_dependencies_flag_applies_added_dependency_and_keeps_the_dependant(tmp_path):
    root = _app_with_users(tmp_path)
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    _write_dependencies(root, "teams", "um:audit")

    result = mitch("up", "--late-dependencies", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert "audit" in tables(tmp_path / "test.db")
    assert "Warning" in result.output and "um:audit" in result.output
    with sqlite3.connect(tmp_path / "test.db") as connection:
        reverted = connection.execute(
            "SELECT count(*) FROM mitch_migration_audit WHERE migration_id = 'teams' AND action = 'reverted'"
        ).fetchone()[0]
    assert reverted == 0


def status_lines(result) -> list[str]:
    return [line for line in result.output.splitlines() if line[:2] in ("A ", "M ", "R ", "- ")]


def test_status_lists_required_linked_migrations_by_alias_and_hides_the_rest(tmp_path):
    root = _app_with_users(tmp_path)

    result = mitch("status", "-p", str(root), "-d", db_url(tmp_path), "--no-ci")

    assert result.exit_code == 0, result.output
    assert status_lines(result) == ["A groups", "A teams", "A um:create-users"]


def test_status_all_also_shows_migrations_of_direct_links_that_are_not_required(tmp_path):
    root = _app_with_users(tmp_path)

    result = mitch("status", "--all", "-p", str(root), "-d", db_url(tmp_path), "--no-ci")

    assert result.exit_code == 0, result.output
    assert "- um:audit" in status_lines(result)


def test_status_names_deeper_migrations_by_their_only_alias_path(tmp_path):
    root = make_project(tmp_path / "app", "app", {"groups": table_with("groups", "users:create-users")})
    users = make_project(root / "users", "org.example.users", {"create-users": table_with("users", "utils:helpers")})
    make_project(users / "utils", "org.example.utils", {"helpers": table("helpers")})

    result = mitch("status", "-p", str(root), "-d", db_url(tmp_path), "--no-ci")

    assert result.exit_code == 0, result.output
    assert "A users:utils:helpers" in status_lines(result)


def test_status_names_migrations_reachable_via_several_paths_by_project_id(tmp_path):
    root = _diamond(tmp_path)

    result = mitch("status", "-p", str(root), "-d", db_url(tmp_path), "--no-ci")

    assert result.exit_code == 0, result.output
    assert "A org.example.utils:helpers" in status_lines(result)


def test_status_fails_ci_for_modified_required_linked_migration_in_strict_mode(tmp_path):
    root = _app_with_users(tmp_path)
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    (tmp_path / "users" / "create-users.up.sql").write_text("CREATE TABLE users (id int, name text);", encoding="utf-8")

    result = mitch("status", "--ci", "--strict", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 3
    assert "M um:create-users" in status_lines(result)


def test_status_reports_missing_only_for_own_migrations(tmp_path):
    root = _app_with_users(tmp_path)
    newer = make_project(
        tmp_path / "other",
        "org.example.other",
        {"profiles": table_with("profiles", "people:extra")},
        links={"people": "vendor/users"},
    )
    make_project(
        newer / "vendor" / "users", "org.example.users", {"create-users": table("users"), "extra": table("extra")}
    )
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    mitch("up", "-p", str(newer), "-d", db_url(tmp_path))

    result = mitch("status", "--ci", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert status_lines(result) == []


def test_log_shows_required_linked_migrations_by_alias(tmp_path):
    root = _app_with_users(tmp_path)
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    result = mitch("log", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert "um:create-users" in result.output
    assert "groups" in result.output


def test_create_accepts_dependency_on_linked_migration(tmp_path):
    root = _app_with_users(tmp_path)

    result = mitch("create", "profiles", "-p", str(root), "-d", "um:create-users")

    assert result.exit_code == 0, result.output
    assert "um:create-users" in (root / "profiles.config.toml").read_text(encoding="utf-8")


def test_create_rejects_unknown_linked_migration(tmp_path):
    root = _app_with_users(tmp_path)

    result = mitch("create", "profiles", "-p", str(root), "-d", "um:nope")

    assert result.exit_code == 1
    assert "um:nope" in result.output
    assert not (root / "profiles.up.sql").exists()


def test_init_rejects_project_id_with_whitespace(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)

    result = mitch("init", "my project")

    assert result.exit_code == 1
    assert not (tmp_path / "mitch.toml").exists()


# ---------------------------------------------------------------- checkout


def _git(cwd: Path, *args: str) -> str:
    import subprocess

    result = subprocess.run(
        ["git", "-c", "protocol.file.allow=always", *args], cwd=cwd, capture_output=True, text=True, check=False
    )
    assert result.returncode == 0, result.stderr or result.stdout
    return result.stdout.strip()


def _git_init(path: Path) -> None:
    _git(path, "init")
    _git(path, "config", "user.email", "test@example.com")
    _git(path, "config", "user.name", "Test User")


def _commit_all(path: Path, message: str) -> None:
    _git(path, "add", ".")
    _git(path, "commit", "-m", message)


def test_checkout_warns_when_nested_linked_project_differs_on_target(tmp_path):
    root = make_project(tmp_path / "app", "app", {"groups": table_with("groups", "users:create-users")})
    users = make_project(root / "users", "org.example.users", {"create-users": table("users")})
    _git_init(root)
    _commit_all(root, "base")
    base = _git(root, "branch", "--show-current")
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    _git(root, "checkout", "-b", "target")
    (users / "create-users.up.sql").write_text("CREATE TABLE users (id int, name text);", encoding="utf-8")
    _commit_all(root, "change linked migration")
    _git(root, "checkout", base)

    result = mitch("checkout", "target", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert _git(root, "branch", "--show-current") == "target"
    assert "Warning" in result.output and "users" in result.output
    assert tables(tmp_path / "test.db") == {"users", "groups"}


def test_checkout_warns_when_submodule_of_linked_project_moves(tmp_path):
    upstream = make_project(tmp_path / "users-upstream", "org.example.users", {"create-users": table("users")})
    _git_init(upstream)
    _commit_all(upstream, "v1")

    root = make_project(tmp_path / "app", "app", {"groups": table_with("groups", "users:create-users")})
    _git_init(root)
    _git(root, "submodule", "add", str(upstream), "users")
    _commit_all(root, "base")
    base = _git(root, "branch", "--show-current")
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    (upstream / "audit.up.sql").write_text("CREATE TABLE audit (id int);", encoding="utf-8")
    _commit_all(upstream, "v2")
    _git(root, "checkout", "-b", "target")
    _git(root / "users", "pull", "origin")
    _commit_all(root, "bump users")
    _git(root, "checkout", base)
    _git(root, "submodule", "update")

    result = mitch("checkout", "target", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert "Warning" in result.output and "users" in result.output


# ---------------------------------------------------------------- review findings


def _other_with_users(tmp_path) -> Path:
    other = make_project(
        tmp_path / "other",
        "org.example.other",
        {"profiles": table_with("profiles", "people:create-users")},
        links={"people": "vendor/users"},
    )
    make_project(
        other / "vendor" / "users", "org.example.users", {"create-users": table("users"), "audit": table("audit")}
    )
    return other


def test_status_with_missing_linked_project_keeps_recorded_dependencies(tmp_path):
    root = _app_with_users(tmp_path)
    other = _other_with_users(tmp_path)
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    mitch("up", "-p", str(other), "-d", db_url(tmp_path))
    (tmp_path / "users").rename(tmp_path / "users-away")

    assert mitch("status", "--no-ci", "-p", str(root), "-d", db_url(tmp_path)).exit_code == 0

    (tmp_path / "users-away").rename(tmp_path / "users")
    result = mitch("down", "-p", str(other), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert "users" in tables(tmp_path / "test.db")


def test_redeploy_keeps_linked_migration_that_its_own_project_applied(tmp_path):
    root = _app_with_users(tmp_path)
    mitch("up", "-p", str(tmp_path / "users"), "-d", db_url(tmp_path))
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    (tmp_path / "users" / "create-users.up.sql").write_text("CREATE TABLE users (id int, name text);", encoding="utf-8")
    assert mitch("up", "-m", "redeploy", "-p", str(root), "-d", db_url(tmp_path)).exit_code == 0

    result = mitch("down", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == {"users", "audit"}


def test_redeploy_is_refused_while_a_project_that_is_not_loaded_depends_on_it(tmp_path):
    root = _app_with_users(tmp_path)
    other = make_project(
        tmp_path / "other",
        "org.example.other",
        {"profiles": table_with("profiles", "people:create-users")},
        links={"people": "../users"},
    )
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    mitch("up", "-p", str(other), "-d", db_url(tmp_path))
    (tmp_path / "users" / "create-users.up.sql").write_text("CREATE TABLE users (id int, name text);", encoding="utf-8")

    result = mitch("up", "-m", "redeploy", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "org.example.other:profiles" in result.output
    assert tables(tmp_path / "test.db") == {"users", "groups", "teams", "profiles"}


def test_status_all_shows_applied_migrations_that_are_not_required(tmp_path):
    root = _app_with_users(tmp_path)
    mitch("up", "-p", str(tmp_path / "users"), "-d", db_url(tmp_path))

    result = mitch("status", "--all", "--no-ci", "-p", str(root), "-d", db_url(tmp_path))

    assert "- um:audit" in status_lines(result)


def test_copies_with_different_dependencies_for_the_same_migration_conflict(tmp_path):
    root = _diamond(
        tmp_path,
        utils_in_b={"helpers": table_with("helpers", "base"), "base": table("base")},
    )

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "differs between copies" in result.output
    assert tables(tmp_path / "test.db") == set()


def test_copy_of_the_root_project_inside_a_linked_project_is_not_own(tmp_path):
    root = make_project(tmp_path / "p", "org.example.p", {"top": table_with("top", "b:in-b")}, links={"b": "../b"})
    b = make_project(tmp_path / "b", "org.example.b", {"in-b": table_with("in_b", "p:extra")}, links={"p": "vendor/p"})
    make_project(
        b / "vendor" / "p",
        "org.example.p",
        {"top": table_with("top", "b:in-b"), "extra": table("extra")},
        links={"b": "../.."},
    )
    assert mitch("up", "-p", str(root), "-d", db_url(tmp_path)).exit_code == 0

    result = mitch("down", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert tables(tmp_path / "test.db") == set()
