"""
Inventory Service - Tenant Data Deletion
Handles deletion of all inventory-related data for a tenant
"""
from typing import Dict
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, delete, func
import structlog

from shared.services.tenant_deletion import BaseTenantDataDeletionService, TenantDataDeletionResult

logger = structlog.get_logger()


class InventoryTenantDeletionService(BaseTenantDataDeletionService):
    """Service for deleting all inventory-related data for a tenant"""

    def __init__(self, db_session: AsyncSession):
        super().__init__("inventory-service")
        self.db = db_session

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

        try:
            preview = {}

            # Import models here to avoid circular imports
            from app.models.inventory import InventoryItem, InventoryTransaction

            # Count inventory items
            item_count = await self.db.scalar(
                select(func.count(InventoryItem.id)).where(InventoryItem.tenant_id == tenant_id)
            )
            preview["inventory_items"] = item_count or 0

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

            return preview

        except Exception as e:
            logger.error("Error getting deletion preview",
                        tenant_id=tenant_id,
                        error=str(e))
            return {}

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

        result = TenantDataDeletionResult(tenant_id, self.service_name)

        try:
            # Import models here to avoid circular imports
            from app.models.inventory import InventoryItem, InventoryTransaction

            # Delete inventory transactions
            try:
                trans_delete = await self.db.execute(
                    delete(InventoryTransaction).where(InventoryTransaction.tenant_id == tenant_id)
                )
                result.add_deleted_items("inventory_transactions", trans_delete.rowcount)
            except Exception as e:
                logger.error("Error deleting inventory transactions",
                           tenant_id=tenant_id,
                           error=str(e))
                result.add_error(f"Inventory transaction deletion: {str(e)}")

            # Delete inventory items
            try:
                item_delete = await self.db.execute(
                    delete(InventoryItem).where(InventoryItem.tenant_id == tenant_id)
                )
                result.add_deleted_items("inventory_items", item_delete.rowcount)
            except Exception as e:
                logger.error("Error deleting inventory items",
                           tenant_id=tenant_id,
                           error=str(e))
                result.add_error(f"Inventory item deletion: {str(e)}")

            # Commit all deletions
            await self.db.commit()

            logger.info("Tenant data deletion completed",
                       tenant_id=tenant_id,
                       deleted_counts=result.deleted_counts)

        except Exception as e:
            logger.error("Fatal error during tenant data deletion",
                        tenant_id=tenant_id,
                        error=str(e))
            await self.db.rollback()
            result.add_error(f"Fatal error: {str(e)}")

        return result
