"""Initial database schema setup migration."""

from app.migrations.migrator import Migration


class Migration(Migration):
    """Initial schema setup with all collections and indexes."""

    def __init__(self):
        super().__init__()
        self.version = "2025-08-17-120000"
        self.description = "Initial database schema with users, jobs, and audit_logs collections"

    async def up(self) -> None:
        """Create initial collections and indexes."""

        # Users collection setup
        await self.db.users.create_index([("email", 1)], unique=True)
        await self.db.users.create_index([("role", 1)])
        await self.db.users.create_index([("is_active", 1)])
        await self.db.users.create_index([("created_at", -1)])

        # Jobs collection setup
        await self.db.jobs.create_index([("status", 1), ("created_at", -1)])
        await self.db.jobs.create_index([("client_id", 1)])
        await self.db.jobs.create_index([("updated_at", -1)])
        await self.db.jobs.create_index([("languages", 1)])

        # Create compound index for job queries
        await self.db.jobs.create_index([
            ("status", 1),
            ("client_id", 1),
            ("created_at", -1)
        ])

        # Audit logs collection setup
        await self.db.audit_logs.create_index([("timestamp", -1)])
        await self.db.audit_logs.create_index([("action", 1), ("timestamp", -1)])
        await self.db.audit_logs.create_index([("user_id", 1), ("timestamp", -1)])
        await self.db.audit_logs.create_index([("severity", 1), ("timestamp", -1)])
        await self.db.audit_logs.create_index([("resource_type", 1), ("resource_id", 1)])
        await self.db.audit_logs.create_index([("ip_address", 1), ("timestamp", -1)])
        await self.db.audit_logs.create_index([("success", 1), ("timestamp", -1)])

        # Text search index for audit logs
        await self.db.audit_logs.create_index([
            ("description", "text"),
            ("details", "text"),
            ("error_message", "text")
        ])

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

    async def down(self) -> None:
        """Drop all collections (destructive - use with caution)."""

        # This is a destructive operation - in production, you might want to backup first
        await self.db.users.drop()
        await self.db.jobs.drop()
        await self.db.audit_logs.drop()

        print(f"⚠️  Rolled back migration {self.version}: {self.description}")
        print("⚠️  WARNING: All data has been deleted!")
