# services/tenant/app/services/messaging.py
"""
Tenant service messaging for event publishing
"""
from shared.messaging.rabbitmq import RabbitMQClient
from app.core.config import settings
import structlog
from datetime import datetime
from typing import Dict, Any

logger = structlog.get_logger()

# Single global instance
data_publisher = RabbitMQClient(settings.RABBITMQ_URL, "data-service")

async def publish_tenant_created(tenant_id: str, owner_id: str, tenant_name: str):
    """Publish tenant created event"""
    try:
        await data_publisher.publish_event(
            "tenant.created",
            {
                "tenant_id": tenant_id,
                "owner_id": owner_id,
                "tenant_name": tenant_name,
                "timestamp": datetime.utcnow().isoformat()
            }
        )
    except Exception as e:
        logger.error(f"Failed to publish tenant.created event: {e}")

async def publish_member_added(tenant_id: str, user_id: str, role: str):
    """Publish member added event"""
    try:
        await data_publisher.publish_event(
            "tenant.member.added",
            {
                "tenant_id": tenant_id,
                "user_id": user_id,
                "role": role,
                "timestamp": datetime.utcnow().isoformat()
            }
        )
    except Exception as e:
        logger.error(f"Failed to publish tenant.member.added event: {e}")
        
async def publish_tenant_deleted_event(tenant_id: str, deletion_stats: Dict[str, Any]):
    """Publish tenant deletion event to message queue"""
    try:
        await data_publisher.publish_event(
            exchange="tenant_events",
            routing_key="tenant.deleted",
            message={
                "event_type": "tenant_deleted",
                "tenant_id": tenant_id,
                "timestamp": datetime.utcnow().isoformat(),
                "deletion_stats": deletion_stats
            }
        )
    except Exception as e:
        logger.error("Failed to publish tenant deletion event", error=str(e))