"""Migration metadata tests."""
from pathlib import Path

from alembic.config import Config
from alembic.script import ScriptDirectory


def test_alembic_revisions_exist():
    root = Path(__file__).resolve().parents[2]
    cfg = Config(str(root / "alembic.ini"))
    cfg.set_main_option("script_location", str(root / "alembic"))
    scripts = ScriptDirectory.from_config(cfg)
    revisions = list(scripts.walk_revisions())
    assert revisions
    assert revisions[0].revision == "0004_phase_63_collaboration"
    assert revisions[-1].revision == "0001_initial"
    assert revisions[-1].down_revision is None


def test_migration_upgrade_creates_metadata_tables(db_setup):
    from app.core.database import Base
    import app.models  # noqa: F401

    expected = {
        "leads",
        "contacts",
        "organizations",
        "pipelines",
        "pipeline_stages",
        "opportunities",
        "sales_activities",
        "quotes",
        "sales_playbooks",
        "sales_forecasts",
        "sales_goals",
        "sales_targets",
        "activity_types",
        "activity_statuses",
        "activity_priorities",
        "activity_participants",
        "activity_reminders",
        "tasks",
        "task_checklists",
        "meetings",
        "meeting_attendees",
        "call_logs",
        "call_outcomes",
        "emails",
        "email_threads",
        "sales_timeline",
        "timeline_events",
        "comments",
        "comment_versions",
        "mentions",
        "bookmarks",
        "favorites",
        "sales_team_members",
        "team_roles",
        "team_assignments",
        "crm_notifications_preferences",
        "sales_collaboration_audit",
    }
    assert expected.issubset(set(Base.metadata.tables.keys()))
