"""
Internal API for Demo Session Service
Handles internal service-to-service operations
"""

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

from app.core import get_db, settings
from app.core.redis_wrapper import get_redis, DemoRedisWrapper
from app.services.cleanup_service import DemoCleanupService

logger = structlog.get_logger()
router = APIRouter()


# ✅ Security: Internal API key system removed
# All authentication now handled via JWT service tokens at gateway level
@router.post("/internal/demo/cleanup")
async def cleanup_demo_session_internal(
    cleanup_request: dict,
    db: AsyncSession = Depends(get_db),
    redis: DemoRedisWrapper = Depends(get_redis)
):
    """
    Internal endpoint to cleanup demo session data for a specific tenant
    Used by rollback mechanisms
    """
    try:
        tenant_id = cleanup_request.get('tenant_id')
        session_id = cleanup_request.get('session_id')

        if not all([tenant_id, session_id]):
            raise HTTPException(
                status_code=400,
                detail="Missing required parameters: tenant_id, session_id"
            )

        logger.info(
            "Internal cleanup requested",
            tenant_id=tenant_id,
            session_id=session_id
        )

        cleanup_service = DemoCleanupService(db, redis)

        # Validate required fields
        if not tenant_id or not session_id:
            raise ValueError("tenant_id and session_id are required")

        # Delete session data for this tenant
        await cleanup_service._delete_tenant_data(
            tenant_id=str(tenant_id),
            session_id=str(session_id)
        )

        # Delete Redis data
        await redis.delete_session_data(str(session_id))

        logger.info(
            "Internal cleanup completed",
            tenant_id=tenant_id,
            session_id=session_id
        )

        return {
            "status": "completed",
            "tenant_id": tenant_id,
            "session_id": session_id
        }

    except Exception as e:
        logger.error(
            "Internal cleanup failed",
            error=str(e),
            tenant_id=cleanup_request.get('tenant_id'),
            session_id=cleanup_request.get('session_id'),
            exc_info=True
        )
        raise HTTPException(status_code=500, detail=f"Failed to cleanup demo session: {str(e)}")
