"""Add PROCESSING_FAILED status to job schema validator and create failure indexes."""
from app.migrations.migrator import Migration


class Migration(Migration):
    version = "2026-04-29-000000"
    description = "Add processing_failed status and failure/status compound indexes on jobs"

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

        # Add processing_failed to the schema validator enum (if validator exists)
        try:
            validator_info = await db.command(
                "listCollections", filter={"name": "jobs"}
            )
            collections = [c async for c in validator_info["cursor"]]
            if collections and collections[0].get("options", {}).get("validator"):
                existing_validator = collections[0]["options"]["validator"]
                status_path = (
                    existing_validator.get("$jsonSchema", {})
                    .get("properties", {})
                    .get("status", {})
                    .get("enum", [])
                )
                if status_path and "processing_failed" not in status_path:
                    status_path.append("processing_failed")
                    await db.command(
                        "collMod",
                        "jobs",
                        validator=existing_validator,
                        validationAction="warn",
                    )
        except Exception:
            # No validator or unsupported — skip gracefully
            pass

        # Indexes for failure dashboard queries
        await db.jobs.create_index(
            [("failure.step", 1), ("status", 1)],
            name="idx_jobs_failure_step_status",
            background=True,
        )
        await db.jobs.create_index(
            [("status", 1), ("organization_id", 1), ("created_at", -1)],
            name="idx_jobs_status_org_created",
            background=True,
        )

    async def down(self) -> None:
        db = self.db
        await db.jobs.drop_index("idx_jobs_failure_step_status")
        await db.jobs.drop_index("idx_jobs_status_org_created")
