"""Backfill Membership.team_ids from Team.member_user_ids (MT-17)."""
from app.migrations.migrator import Migration


class Migration(Migration):
    version = "2026-04-30-000000"
    description = "Backfill team_ids on Membership records from Team.member_user_ids"

    async def up(self) -> None:
        db = self.db
        upserted = 0

        # For each team that has member_user_ids, push team_id into the matching Membership
        async for team in db.teams.find(
            {"member_user_ids": {"$exists": True, "$ne": []}},
            {"_id": 1, "client_id": 1, "member_user_ids": 1},
        ):
            team_id = str(team["_id"])
            org_id = str(team.get("client_id", ""))
            for user_id in team.get("member_user_ids", []):
                result = await db.memberships.update_one(
                    {"user_id": str(user_id), "organization_id": org_id},
                    {"$addToSet": {"team_ids": team_id}},
                )
                if result.modified_count:
                    upserted += 1

        # Ensure index for efficient team-based lookups
        await db.memberships.create_index(
            [("team_ids", 1)],
            name="idx_memberships_team_ids",
            background=True,
            sparse=True,
        )

        print(f"✅ Backfilled team_ids on {upserted} Membership records")

    async def down(self) -> None:
        db = self.db
        await db.memberships.update_many({}, {"$unset": {"team_ids": ""}})
        try:
            await db.memberships.drop_index("idx_memberships_team_ids")
        except Exception:
            pass
