"""Add cancelled status to job schema validator."""
from app.migrations.migrator import Migration


class Migration(Migration):
    version = "2026-04-30-000001"
    description = "Add cancelled status to jobs collection schema validator"

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

        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 "cancelled" not in status_path:
                    status_path.append("cancelled")
                    await db.command(
                        "collMod",
                        "jobs",
                        validator=existing_validator,
                        validationAction="warn",
                    )
        except Exception:
            # No validator or unsupported — skip gracefully
            pass

    async def down(self) -> None:
        pass
