# services/production/app/api/production_orders_operations.py
"""
Tenant Data Deletion Operations (Internal Service Only)
"""

from fastapi import APIRouter, Depends, HTTPException, Path
from sqlalchemy.ext.asyncio import AsyncSession
import structlog

from shared.auth.decorators import get_current_user_dep
from shared.auth.access_control import service_only_access
from shared.routing import RouteBuilder
from shared.services.tenant_deletion import TenantDataDeletionResult
from app.core.database import get_db
from app.services.tenant_deletion_service import ProductionTenantDeletionService

logger = structlog.get_logger()
route_builder = RouteBuilder('production')
router = APIRouter(tags=["production-tenant-deletion"])


@router.delete(
    route_builder.build_base_route("tenant/{tenant_id}", include_tenant_prefix=False),
    response_model=dict
)
@service_only_access
async def delete_tenant_data(
    tenant_id: str = Path(..., description="Tenant ID to delete data for"),
    current_user: dict = Depends(get_current_user_dep),
    db: AsyncSession = Depends(get_db)
):
    """
    Delete all production data for a tenant (Internal service only)
    """
    try:
        logger.info("production.tenant_deletion.api_called", tenant_id=tenant_id)

        deletion_service = ProductionTenantDeletionService(db)
        result = await deletion_service.safe_delete_tenant_data(tenant_id)

        if not result.success:
            raise HTTPException(
                status_code=500,
                detail=f"Tenant data deletion failed: {', '.join(result.errors)}"
            )

        return {
            "message": "Tenant data deletion completed successfully",
            "summary": result.to_dict()
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error("production.tenant_deletion.api_error", tenant_id=tenant_id, error=str(e), exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to delete tenant data: {str(e)}")


@router.get(
    route_builder.build_base_route("tenant/{tenant_id}/deletion-preview", include_tenant_prefix=False),
    response_model=dict
)
@service_only_access
async def preview_tenant_data_deletion(
    tenant_id: str = Path(..., description="Tenant ID to preview deletion for"),
    current_user: dict = Depends(get_current_user_dep),
    db: AsyncSession = Depends(get_db)
):
    """
    Preview what data would be deleted for a tenant (dry-run)
    """
    try:
        logger.info("production.tenant_deletion.preview_called", tenant_id=tenant_id)

        deletion_service = ProductionTenantDeletionService(db)
        preview_data = await deletion_service.get_tenant_data_preview(tenant_id)
        result = TenantDataDeletionResult(tenant_id=tenant_id, service_name=deletion_service.service_name)
        result.deleted_counts = preview_data
        result.success = True

        if not result.success:
            raise HTTPException(
                status_code=500,
                detail=f"Tenant deletion preview failed: {', '.join(result.errors)}"
            )

        return {
            "tenant_id": tenant_id,
            "service": "production-service",
            "data_counts": result.deleted_counts,
            "total_items": sum(result.deleted_counts.values())
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error("production.tenant_deletion.preview_error", tenant_id=tenant_id, error=str(e), exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to preview tenant data deletion: {str(e)}")
