"""
Recipes Service - Tenant Data Deletion
Handles deletion of all recipe-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
from app.models.recipes import Recipe, RecipeIngredient, ProductionBatch

logger = structlog.get_logger()


class RecipesTenantDeletionService(BaseTenantDataDeletionService):
    """Service for deleting all recipe-related data for a tenant"""

    def __init__(self, db_session: AsyncSession):
        super().__init__("recipes-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 = {}

            # Count recipes
            recipe_count = await self.db.scalar(
                select(func.count(Recipe.id)).where(Recipe.tenant_id == tenant_id)
            )
            preview["recipes"] = recipe_count or 0

            # Count recipe ingredients (will be deleted via CASCADE)
            ingredient_count = await self.db.scalar(
                select(func.count(RecipeIngredient.id))
                .where(RecipeIngredient.tenant_id == tenant_id)
            )
            preview["recipe_ingredients"] = ingredient_count or 0

            # Count production batches (will be deleted via CASCADE)
            batch_count = await self.db.scalar(
                select(func.count(ProductionBatch.id))
                .where(ProductionBatch.tenant_id == tenant_id)
            )
            preview["production_batches"] = batch_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:
            # Get preview before deletion for reporting
            preview = await self.get_tenant_data_preview(tenant_id)

            # Delete production batches first (foreign key to recipes)
            try:
                batch_delete = await self.db.execute(
                    delete(ProductionBatch).where(ProductionBatch.tenant_id == tenant_id)
                )
                deleted_batches = batch_delete.rowcount
                result.add_deleted_items("production_batches", deleted_batches)

                logger.info("Deleted production batches for tenant",
                           tenant_id=tenant_id,
                           count=deleted_batches)

            except Exception as e:
                logger.error("Error deleting production batches",
                           tenant_id=tenant_id,
                           error=str(e))
                result.add_error(f"Production batch deletion: {str(e)}")

            # Delete recipe ingredients (foreign key to recipes)
            try:
                ingredient_delete = await self.db.execute(
                    delete(RecipeIngredient).where(RecipeIngredient.tenant_id == tenant_id)
                )
                deleted_ingredients = ingredient_delete.rowcount
                result.add_deleted_items("recipe_ingredients", deleted_ingredients)

                logger.info("Deleted recipe ingredients for tenant",
                           tenant_id=tenant_id,
                           count=deleted_ingredients)

            except Exception as e:
                logger.error("Error deleting recipe ingredients",
                           tenant_id=tenant_id,
                           error=str(e))
                result.add_error(f"Recipe ingredient deletion: {str(e)}")

            # Delete recipes (parent table)
            try:
                recipe_delete = await self.db.execute(
                    delete(Recipe).where(Recipe.tenant_id == tenant_id)
                )
                deleted_recipes = recipe_delete.rowcount
                result.add_deleted_items("recipes", deleted_recipes)

                logger.info("Deleted recipes for tenant",
                           tenant_id=tenant_id,
                           count=deleted_recipes)

            except Exception as e:
                logger.error("Error deleting recipes",
                           tenant_id=tenant_id,
                           error=str(e))
                result.add_error(f"Recipe 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
