"""
POS routes for API Gateway - Global POS endpoints
"""

from fastapi import APIRouter, Request, Response, HTTPException
from fastapi.responses import JSONResponse
import httpx
import logging

from app.core.config import settings
from app.core.header_manager import header_manager

logger = logging.getLogger(__name__)
router = APIRouter()

# ================================================================
# GLOBAL POS ENDPOINTS (No tenant context required)
# ================================================================

@router.api_route("/supported-systems", methods=["GET", "OPTIONS"])
async def proxy_supported_systems(request: Request):
    """Proxy supported POS systems request to POS service"""
    target_path = "/api/v1/pos/supported-systems"
    return await _proxy_to_pos_service(request, target_path)

# ================================================================
# PROXY HELPER FUNCTIONS
# ================================================================

async def _proxy_to_pos_service(request: Request, target_path: str):
    """Proxy request to POS service"""

    # Handle OPTIONS requests directly for CORS
    if request.method == "OPTIONS":
        return Response(
            status_code=200,
            headers={
                "Access-Control-Allow-Origin": settings.CORS_ORIGINS_LIST,
                "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
                "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Tenant-ID",
                "Access-Control-Allow-Credentials": "true",
                "Access-Control-Max-Age": "86400"
            }
        )

    try:
        url = f"{settings.POS_SERVICE_URL}{target_path}"

        # Use unified HeaderManager for consistent header forwarding
        headers = header_manager.get_all_headers_for_proxy(request)

        # Add query parameters
        params = dict(request.query_params)

        timeout_config = httpx.Timeout(
            connect=30.0,
            read=60.0,
            write=30.0,
            pool=30.0
        )

        async with httpx.AsyncClient(timeout=timeout_config) as client:
            response = await client.request(
                method=request.method,
                url=url,
                headers=headers,
                params=params
            )

            # Handle different response types
            if response.headers.get("content-type", "").startswith("application/json"):
                try:
                    content = response.json()
                except:
                    content = {"message": "Invalid JSON response from service"}
            else:
                content = response.text

            return JSONResponse(
                status_code=response.status_code,
                content=content
            )

    except Exception as e:
        logger.error(f"Unexpected error proxying to POS service {target_path}: {e}")
        raise HTTPException(
            status_code=500,
            detail="Internal gateway error"
        )
