"""Index optimization migration for improved query performance."""

from app.migrations.migrator import Migration


class Migration(Migration):
    """Optimize indexes for better query performance."""

    def __init__(self):
        super().__init__()
        self.version = "2025-08-17-120001"
        self.description = "Index optimization for query performance improvements"

    async def up(self) -> None:
        """Add optimized indexes for common query patterns."""

        # Jobs collection optimizations

        # Index for job status transitions and monitoring
        await self.db.jobs.create_index([
            ("status", 1),
            ("updated_at", -1),
            ("client_id", 1)
        ], name="jobs_status_updated_client_idx")

        # Index for queue management (pending jobs)
        await self.db.jobs.create_index([
            ("status", 1),
            ("created_at", 1)
        ], name="jobs_queue_processing_idx")

        # Index for client job history
        await self.db.jobs.create_index([
            ("client_id", 1),
            ("created_at", -1),
            ("status", 1)
        ], name="jobs_client_history_idx")

        # Sparse index for error tracking
        await self.db.jobs.create_index([
            ("status", 1),
            ("error", 1)
        ], sparse=True, name="jobs_error_tracking_idx")

        # Users collection optimizations

        # Index for active user queries
        await self.db.users.create_index([
            ("is_active", 1),
            ("role", 1),
            ("last_login_at", -1)
        ], name="users_active_role_login_idx")

        # Index for user search by email pattern
        await self.db.users.create_index([
            ("email", "text"),
            ("first_name", "text"),
            ("last_name", "text")
        ], name="users_search_idx")

        # Audit logs collection optimizations

        # Compound index for security monitoring
        await self.db.audit_logs.create_index([
            ("severity", 1),
            ("action", 1),
            ("timestamp", -1)
        ], name="audit_security_monitoring_idx")

        # Index for user activity analysis
        await self.db.audit_logs.create_index([
            ("user_id", 1),
            ("action", 1),
            ("timestamp", -1)
        ], name="audit_user_activity_idx")

        # Index for resource access tracking
        await self.db.audit_logs.create_index([
            ("resource_type", 1),
            ("resource_id", 1),
            ("action", 1),
            ("timestamp", -1)
        ], name="audit_resource_access_idx")

        # Sparse index for failed operations
        await self.db.audit_logs.create_index([
            ("success", 1),
            ("timestamp", -1)
        ], sparse=True, name="audit_failures_idx")

        # Add TTL index for automatic audit log cleanup (optional)
        # Uncomment if you want automatic cleanup after 2 years
        # await self.db.audit_logs.create_index(
        #     [("timestamp", 1)],
        #     expireAfterSeconds=63072000,  # 2 years
        #     name="audit_ttl_idx"
        # )

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

    async def down(self) -> None:
        """Remove the optimized indexes."""

        # Drop the indexes we created
        indexes_to_drop = [
            "jobs_status_updated_client_idx",
            "jobs_queue_processing_idx",
            "jobs_client_history_idx",
            "jobs_error_tracking_idx",
            "users_active_role_login_idx",
            "users_search_idx",
            "audit_security_monitoring_idx",
            "audit_user_activity_idx",
            "audit_resource_access_idx",
            "audit_failures_idx"
        ]

        for index_name in indexes_to_drop:
            try:
                await self.db.jobs.drop_index(index_name)
            except Exception:
                pass  # Index might not exist on this collection

            try:
                await self.db.users.drop_index(index_name)
            except Exception:
                pass

            try:
                await self.db.audit_logs.drop_index(index_name)
            except Exception:
                pass

        print(f"⚠️  Rolled back migration {self.version}: {self.description}")
