# services/alert_processor/app/services/tenant_deletion_service.py
"""
Tenant Data Deletion Service for Alert Processor Service
Handles deletion of all alert-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 Alert, AuditLog

logger = structlog.get_logger(__name__)


class AlertProcessorTenantDeletionService(BaseTenantDataDeletionService):
    """Service for deleting all alert-related data for a tenant"""

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

    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("alert_processor.tenant_deletion.preview", tenant_id=tenant_id)
        preview = {}

        try:
            # Count alerts (CASCADE will delete alert_interactions)
            alert_count = await self.db.scalar(
                select(func.count(Alert.id)).where(
                    Alert.tenant_id == tenant_id
                )
            )
            preview["alerts"] = alert_count or 0

            # Note: AlertInteraction has CASCADE delete, so counting manually
            # Count alert interactions for informational purposes
            from app.models.alerts import AlertInteraction
            interaction_count = await self.db.scalar(
                select(func.count(AlertInteraction.id)).where(
                    AlertInteraction.tenant_id == tenant_id
                )
            )
            preview["alert_interactions"] = interaction_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(
                "alert_processor.tenant_deletion.preview_complete",
                tenant_id=tenant_id,
                preview=preview
            )

        except Exception as e:
            logger.error(
                "alert_processor.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 alert data for a tenant

        Deletion order (respecting foreign key constraints):
        1. AlertInteraction (child of Alert with CASCADE, but deleted explicitly for tracking)
        2. Alert (parent table)
        3. AuditLog (independent)

        Note: AlertInteraction has CASCADE delete from Alert, so it will be
        automatically deleted when Alert is deleted. We delete it explicitly
        first for proper counting and logging.

        Args:
            tenant_id: The tenant ID to delete data for

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

        try:
            # Import AlertInteraction here to avoid circular imports
            from app.models.alerts import AlertInteraction

            # Step 1: Delete alert interactions (child of alerts)
            logger.info("alert_processor.tenant_deletion.deleting_interactions", tenant_id=tenant_id)
            interactions_result = await self.db.execute(
                delete(AlertInteraction).where(
                    AlertInteraction.tenant_id == tenant_id
                )
            )
            result.deleted_counts["alert_interactions"] = interactions_result.rowcount
            logger.info(
                "alert_processor.tenant_deletion.interactions_deleted",
                tenant_id=tenant_id,
                count=interactions_result.rowcount
            )

            # Step 2: Delete alerts
            logger.info("alert_processor.tenant_deletion.deleting_alerts", tenant_id=tenant_id)
            alerts_result = await self.db.execute(
                delete(Alert).where(
                    Alert.tenant_id == tenant_id
                )
            )
            result.deleted_counts["alerts"] = alerts_result.rowcount
            logger.info(
                "alert_processor.tenant_deletion.alerts_deleted",
                tenant_id=tenant_id,
                count=alerts_result.rowcount
            )

            # Step 3: Delete audit logs
            logger.info("alert_processor.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(
                "alert_processor.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(
                "alert_processor.tenant_deletion.completed",
                tenant_id=tenant_id,
                total_deleted=total_deleted,
                breakdown=result.deleted_counts
            )

            result.success = True

        except Exception as e:
            await self.db.rollback()
            error_msg = f"Failed to delete alert data for tenant {tenant_id}: {str(e)}"
            logger.error(
                "alert_processor.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_alert_processor_tenant_deletion_service(
    db: AsyncSession
) -> AlertProcessorTenantDeletionService:
    """
    Factory function to create AlertProcessorTenantDeletionService instance

    Args:
        db: AsyncSession database session

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