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

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

from shared.services.tenant_deletion import (
    BaseTenantDataDeletionService,
    TenantDataDeletionResult
)
from app.models import (
    POSConfiguration,
    POSTransaction,
    POSTransactionItem,
    POSWebhookLog,
    POSSyncLog,
    AuditLog
)

logger = structlog.get_logger(__name__)


class POSTenantDeletionService(BaseTenantDataDeletionService):
    """Service for deleting all POS-related data for a tenant"""

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

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

        try:
            # Count POS configurations
            config_count = await self.db.scalar(
                select(func.count(POSConfiguration.id)).where(
                    POSConfiguration.tenant_id == tenant_id
                )
            )
            preview["pos_configurations"] = config_count or 0

            # Count POS transactions
            transaction_count = await self.db.scalar(
                select(func.count(POSTransaction.id)).where(
                    POSTransaction.tenant_id == tenant_id
                )
            )
            preview["pos_transactions"] = transaction_count or 0

            # Count POS transaction items
            item_count = await self.db.scalar(
                select(func.count(POSTransactionItem.id)).where(
                    POSTransactionItem.tenant_id == tenant_id
                )
            )
            preview["pos_transaction_items"] = item_count or 0

            # Count webhook logs
            webhook_count = await self.db.scalar(
                select(func.count(POSWebhookLog.id)).where(
                    POSWebhookLog.tenant_id == tenant_id
                )
            )
            preview["pos_webhook_logs"] = webhook_count or 0

            # Count sync logs
            sync_count = await self.db.scalar(
                select(func.count(POSSyncLog.id)).where(
                    POSSyncLog.tenant_id == tenant_id
                )
            )
            preview["pos_sync_logs"] = sync_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(
                "pos.tenant_deletion.preview_complete",
                tenant_id=tenant_id,
                preview=preview
            )

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

        Deletion order (respecting foreign key constraints):
        1. POSTransactionItem (references POSTransaction)
        2. POSTransaction (references POSConfiguration)
        3. POSWebhookLog (independent)
        4. POSSyncLog (references POSConfiguration)
        5. POSConfiguration (base configuration)
        6. AuditLog (independent)

        Args:
            tenant_id: The tenant ID to delete data for

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

        try:
            # Step 1: Delete POS transaction items (child of transactions)
            logger.info("pos.tenant_deletion.deleting_transaction_items", tenant_id=tenant_id)
            items_result = await self.db.execute(
                delete(POSTransactionItem).where(
                    POSTransactionItem.tenant_id == tenant_id
                )
            )
            result.deleted_counts["pos_transaction_items"] = items_result.rowcount
            logger.info(
                "pos.tenant_deletion.transaction_items_deleted",
                tenant_id=tenant_id,
                count=items_result.rowcount
            )

            # Step 2: Delete POS transactions
            logger.info("pos.tenant_deletion.deleting_transactions", tenant_id=tenant_id)
            transactions_result = await self.db.execute(
                delete(POSTransaction).where(
                    POSTransaction.tenant_id == tenant_id
                )
            )
            result.deleted_counts["pos_transactions"] = transactions_result.rowcount
            logger.info(
                "pos.tenant_deletion.transactions_deleted",
                tenant_id=tenant_id,
                count=transactions_result.rowcount
            )

            # Step 3: Delete webhook logs
            logger.info("pos.tenant_deletion.deleting_webhook_logs", tenant_id=tenant_id)
            webhook_result = await self.db.execute(
                delete(POSWebhookLog).where(
                    POSWebhookLog.tenant_id == tenant_id
                )
            )
            result.deleted_counts["pos_webhook_logs"] = webhook_result.rowcount
            logger.info(
                "pos.tenant_deletion.webhook_logs_deleted",
                tenant_id=tenant_id,
                count=webhook_result.rowcount
            )

            # Step 4: Delete sync logs
            logger.info("pos.tenant_deletion.deleting_sync_logs", tenant_id=tenant_id)
            sync_result = await self.db.execute(
                delete(POSSyncLog).where(
                    POSSyncLog.tenant_id == tenant_id
                )
            )
            result.deleted_counts["pos_sync_logs"] = sync_result.rowcount
            logger.info(
                "pos.tenant_deletion.sync_logs_deleted",
                tenant_id=tenant_id,
                count=sync_result.rowcount
            )

            # Step 5: Delete POS configurations (last, as it's referenced by transactions and sync logs)
            logger.info("pos.tenant_deletion.deleting_configurations", tenant_id=tenant_id)
            config_result = await self.db.execute(
                delete(POSConfiguration).where(
                    POSConfiguration.tenant_id == tenant_id
                )
            )
            result.deleted_counts["pos_configurations"] = config_result.rowcount
            logger.info(
                "pos.tenant_deletion.configurations_deleted",
                tenant_id=tenant_id,
                count=config_result.rowcount
            )

            # Step 6: Delete audit logs
            logger.info("pos.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(
                "pos.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(
                "pos.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 POS data for tenant {tenant_id}: {str(e)}"
            logger.error(
                "pos.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_pos_tenant_deletion_service(db: AsyncSession) -> POSTenantDeletionService:
    """
    Factory function to create POSTenantDeletionService instance

    Args:
        db: AsyncSession database session

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