"""
Connector API Routes for Ingress and Egress
- Ingress: Amazon sends consultation requests directly via API
- Egress: Send responses to Amazon's API (when egress flag is enabled)
"""

import logging
import time

from fastapi import APIRouter, HTTPException, Request

from app.src.token_auth import validate_bearer_token

logger = logging.getLogger(__name__)

router = APIRouter()


@router.post("/orders")
async def handle_ingress(request: Request):
    """Receive consultation request from Amazon via API.

    Amazon calls this endpoint with a Bearer JWT token in the Authorization header.
    The token is validated by:
    1. Checking expiry (exp > current time)
    2. Extracting and decrypting vendorUid
    3. Comparing decrypted vendorUid with the expected Amazon API key
    """
    try:
        config = request.app.state.file_processor.config

        if config.ingress_mode not in ("both", "api"):
            raise HTTPException(
                status_code=403,
                detail="Ingress API is not enabled. Set INGRESS_MODE=both or INGRESS_MODE=api to use this endpoint.",
            )

        # Validate Bearer token
        authorization = request.headers.get("Authorization")
        auth_result = validate_bearer_token(authorization, config.rx_api_key)

        if not auth_result["valid"]:
            logger.warning("Token validation failed: %s", auth_result["error"])
            raise HTTPException(status_code=401, detail=auth_result["error"])

        logger.info(
            "Token validated for vendor: %s",
            auth_result["payload"].get("vendorId"),
        )

        amazon_request = await request.json()
        message_ids = amazon_request.get("messageIdentifiers", {})
        logger.info(
            "Received ingress API request, trackingId: %s, primaryReferenceId: %s",
            message_ids.get("trackingId"),
            message_ids.get("primaryReferenceId"),
        )

        # Validate required fields (new schema)
        if not message_ids.get("trackingId"):
            raise HTTPException(
                status_code=400,
                detail="Missing messageIdentifiers.trackingId",
            )
        if not message_ids.get("primaryReferenceId"):
            raise HTTPException(
                status_code=400,
                detail="Missing messageIdentifiers.primaryReferenceId",
            )

        file_processor = request.app.state.file_processor
        result = await file_processor.process_api_request(amazon_request)

        if result.get("success"):
            return {
                "messageIdentifiers": result["message_identifiers"],
                "consultationCreationStatus": "CREATED",
                "acknowledgementTimeStamp": int(time.time() * 1000),
            }
        else:
            return {
                "messageIdentifiers": result.get("message_identifiers", message_ids),
                "consultationCreationStatus": "ERRORED",
                "acknowledgementTimeStamp": int(time.time() * 1000),
                "errorMessage": result.get("error", "Failed to process request"),
            }

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error handling ingress request: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/egress")
async def handle_egress(request: Request):
    """Send consultation response to Amazon via API.

    This replaces the SFTP upload flow when egress_api_enabled=True.
    Currently not implemented (egress_api_enabled=False).
    Responses are still sent via SFTP.
    """
    config = request.app.state.file_processor.config

    if not config.egress_api_enabled:
        raise HTTPException(
            status_code=403,
            detail="Egress API is not enabled. Responses are sent via SFTP.",
        )

    # Future implementation: when egress_api_enabled=True,
    # this endpoint will send the response to Amazon's API
    raise HTTPException(
        status_code=501,
        detail="Egress API not yet implemented. Responses are sent via SFTP.",
    )
