"""Add auth_provider field to users collection."""

from app.migrations.migrator import Migration


class Migration(Migration):
    """Add auth_provider field to support Microsoft authentication."""

    def __init__(self):
        super().__init__()
        self.version = "2025-10-10-000000"
        self.description = "Add auth_provider field to users collection"

    async def up(self) -> None:
        """Add auth_provider field to all users."""

        # Add auth_provider field to all existing users (default to 'local')
        result = await self.db.users.update_many(
            {"auth_provider": {"$exists": False}},
            {"$set": {"auth_provider": "local"}}
        )

        print(f"✅ Updated {result.modified_count} users with auth_provider='local'")

        # Create index on auth_provider for faster queries
        await self.db.users.create_index([("auth_provider", 1)])
        print("✅ Created index on auth_provider field")

        print(f"✅ Applied migration {self.version}: {self.description}")

    async def down(self) -> None:
        """Remove auth_provider field from all users."""

        # Drop the index
        try:
            await self.db.users.drop_index("auth_provider_1")
            print("✅ Dropped index on auth_provider field")
        except Exception as e:
            print(f"⚠️  Could not drop index: {e}")

        # Remove auth_provider field from all users
        result = await self.db.users.update_many(
            {},
            {"$unset": {"auth_provider": ""}}
        )

        print(f"✅ Removed auth_provider field from {result.modified_count} users")
        print(f"⚠️  Rolled back migration {self.version}: {self.description}")
