# services/notification/app/services/tenant_deletion_service.py
"""
Tenant Data Deletion Service for Notification Service
Handles deletion of all notification-related data for a tenant
"""

from typing import Dict
from sqlalchemy import select, func, delete
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.dialects.postgresql import UUID
import structlog

from shared.services.tenant_deletion import (
    BaseTenantDataDeletionService,
    TenantDataDeletionResult
)
from app.models import (
    Notification,
    NotificationTemplate,
    NotificationPreference,
    NotificationLog,
    AuditLog
)

logger = structlog.get_logger(__name__)


class NotificationTenantDeletionService(BaseTenantDataDeletionService):
    """Service for deleting all notification-related data for a tenant"""

    def __init__(self, db: AsyncSession):
        self.db = db
        self.service_name = "notification"

    async def get_tenant_data_preview(self, tenant_id: str) -> Dict[str, int]:
        """
        Get counts of what would be deleted for a tenant (dry-run)

        Args:
            tenant_id: The tenant ID to preview deletion for

        Returns:
            Dictionary with entity names and their counts
        """
        logger.info("notification.tenant_deletion.preview", tenant_id=tenant_id)
        preview = {}

        try:
            # Count notifications
            notification_count = await self.db.scalar(
                select(func.count(Notification.id)).where(
                    Notification.tenant_id == tenant_id
                )
            )
            preview["notifications"] = notification_count or 0

            # Count tenant-specific notification templates
            template_count = await self.db.scalar(
                select(func.count(NotificationTemplate.id)).where(
                    NotificationTemplate.tenant_id == tenant_id,
                    NotificationTemplate.is_system == False  # Don't delete system templates
                )
            )
            preview["notification_templates"] = template_count or 0

            # Count notification preferences
            preference_count = await self.db.scalar(
                select(func.count(NotificationPreference.id)).where(
                    NotificationPreference.tenant_id == tenant_id
                )
            )
            preview["notification_preferences"] = preference_count or 0

            # Count notification logs (join with Notification to get tenant_id)
            log_count = await self.db.scalar(
                select(func.count(NotificationLog.id)).select_from(NotificationLog).join(
                    Notification, NotificationLog.notification_id == Notification.id
                ).where(
                    Notification.tenant_id == tenant_id
                )
            )
            preview["notification_logs"] = log_count or 0

            # Count audit logs
            audit_count = await self.db.scalar(
                select(func.count(AuditLog.id)).where(
                    AuditLog.tenant_id == tenant_id
                )
            )
            preview["audit_logs"] = audit_count or 0

            logger.info(
                "notification.tenant_deletion.preview_complete",
                tenant_id=tenant_id,
                preview=preview
            )

        except Exception as e:
            logger.error(
                "notification.tenant_deletion.preview_error",
                tenant_id=tenant_id,
                error=str(e),
                exc_info=True
            )
            raise

        return preview

    async def delete_tenant_data(self, tenant_id: str) -> TenantDataDeletionResult:
        """
        Permanently delete all notification data for a tenant

        Deletion order:
        1. NotificationLog (independent)
        2. NotificationPreference (independent)
        3. Notification (main records)
        4. NotificationTemplate (only tenant-specific, preserve system templates)
        5. AuditLog (independent)

        Note: System templates (is_system=True) are NOT deleted

        Args:
            tenant_id: The tenant ID to delete data for

        Returns:
            TenantDataDeletionResult with deletion counts and any errors
        """
        logger.info("notification.tenant_deletion.started", tenant_id=tenant_id)
        result = TenantDataDeletionResult(tenant_id=tenant_id, service_name=self.service_name)

        try:
            # Step 1: Delete notification logs (via subquery to get notification_ids for this tenant)
            logger.info("notification.tenant_deletion.deleting_logs", tenant_id=tenant_id)
            notification_ids_subquery = select(Notification.id).where(Notification.tenant_id == tenant_id)
            logs_result = await self.db.execute(
                delete(NotificationLog).where(
                    NotificationLog.notification_id.in_(notification_ids_subquery)
                )
            )
            result.deleted_counts["notification_logs"] = logs_result.rowcount
            logger.info(
                "notification.tenant_deletion.logs_deleted",
                tenant_id=tenant_id,
                count=logs_result.rowcount
            )

            # Step 2: Delete notification preferences
            logger.info("notification.tenant_deletion.deleting_preferences", tenant_id=tenant_id)
            preferences_result = await self.db.execute(
                delete(NotificationPreference).where(
                    NotificationPreference.tenant_id == tenant_id
                )
            )
            result.deleted_counts["notification_preferences"] = preferences_result.rowcount
            logger.info(
                "notification.tenant_deletion.preferences_deleted",
                tenant_id=tenant_id,
                count=preferences_result.rowcount
            )

            # Step 3: Delete notifications
            logger.info("notification.tenant_deletion.deleting_notifications", tenant_id=tenant_id)
            notifications_result = await self.db.execute(
                delete(Notification).where(
                    Notification.tenant_id == tenant_id
                )
            )
            result.deleted_counts["notifications"] = notifications_result.rowcount
            logger.info(
                "notification.tenant_deletion.notifications_deleted",
                tenant_id=tenant_id,
                count=notifications_result.rowcount
            )

            # Step 4: Delete tenant-specific templates (preserve system templates)
            logger.info("notification.tenant_deletion.deleting_templates", tenant_id=tenant_id)
            templates_result = await self.db.execute(
                delete(NotificationTemplate).where(
                    NotificationTemplate.tenant_id == tenant_id,
                    NotificationTemplate.is_system == False
                )
            )
            result.deleted_counts["notification_templates"] = templates_result.rowcount
            logger.info(
                "notification.tenant_deletion.templates_deleted",
                tenant_id=tenant_id,
                count=templates_result.rowcount,
                note="System templates preserved"
            )

            # Step 5: Delete audit logs
            logger.info("notification.tenant_deletion.deleting_audit_logs", tenant_id=tenant_id)
            audit_result = await self.db.execute(
                delete(AuditLog).where(
                    AuditLog.tenant_id == tenant_id
                )
            )
            result.deleted_counts["audit_logs"] = audit_result.rowcount
            logger.info(
                "notification.tenant_deletion.audit_logs_deleted",
                tenant_id=tenant_id,
                count=audit_result.rowcount
            )

            # Commit the transaction
            await self.db.commit()

            # Calculate total deleted
            total_deleted = sum(result.deleted_counts.values())

            logger.info(
                "notification.tenant_deletion.completed",
                tenant_id=tenant_id,
                total_deleted=total_deleted,
                breakdown=result.deleted_counts,
                note="System templates preserved"
            )

            result.success = True

        except Exception as e:
            await self.db.rollback()
            error_msg = f"Failed to delete notification data for tenant {tenant_id}: {str(e)}"
            logger.error(
                "notification.tenant_deletion.failed",
                tenant_id=tenant_id,
                error=str(e),
                exc_info=True
            )
            result.errors.append(error_msg)
            result.success = False

        return result


def get_notification_tenant_deletion_service(
    db: AsyncSession
) -> NotificationTenantDeletionService:
    """
    Factory function to create NotificationTenantDeletionService instance

    Args:
        db: AsyncSession database session

    Returns:
        NotificationTenantDeletionService instance
    """
    return NotificationTenantDeletionService(db)
