"""Backfill organization_id on jobs from their project's client_id."""

from app.migrations.migrator import Migration


class Migration(Migration):

    def __init__(self):
        super().__init__()
        self.version = "2026-04-28-000003"
        self.description = "Backfill job.organization_id from project.client_id"

    async def up(self) -> None:
        updated = 0
        skipped = 0

        async for job in self.db.jobs.find(
            {"organization_id": {"$exists": False}},
            {"_id": 1, "project_id": 1, "client_id": 1},
        ):
            org_id = None

            project_id = job.get("project_id")
            if project_id:
                project = await self.db.projects.find_one({"_id": project_id}, {"client_id": 1})
                if project:
                    org_id = project.get("client_id")

            # Fallback: client_id on the job currently stores the user id, not org id
            # We do NOT copy client_id directly — set organization_id only from project
            if not org_id:
                skipped += 1
                continue

            await self.db.jobs.update_one(
                {"_id": job["_id"]},
                {"$set": {"organization_id": org_id}},
            )
            updated += 1

        # Add sparse index on organization_id for future OrgScopedQuery usage
        await self.db.jobs.create_index(
            [("organization_id", 1), ("status", 1), ("created_at", -1)],
            name="org_status_created",
            sparse=True,
        )

        print(f"✅ Backfilled organization_id on {updated} jobs ({skipped} skipped — no project)")
        print(f"✅ Applied migration {self.version}: {self.description}")

    async def down(self) -> None:
        result = await self.db.jobs.update_many(
            {"organization_id": {"$exists": True}},
            {"$unset": {"organization_id": ""}},
        )
        try:
            await self.db.jobs.drop_index("org_status_created")
        except Exception:
            pass
        print(f"⚠️  Rolled back migration {self.version}: removed organization_id from {result.modified_count} jobs")
