# app/modules/orders/routes/api/admin.py
"""
Admin order management endpoints.

Provides order management capabilities for administrators:
- View orders across all stores
- View store-specific orders
- Update order status on behalf of stores
- Order statistics and reporting

Admin Context: Uses admin JWT authentication.
Store selection is passed as a request parameter.

This router aggregates both order routes and exception routes.
"""

import logging

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.api.deps import get_current_admin_api, require_module_access
from app.core.database import get_db
from app.modules.enums import FrontendType
from app.modules.orders.schemas import (
    AdminOrderItem,
    AdminOrderListResponse,
    AdminOrderStats,
    AdminOrderStatusUpdate,
    AdminStoresWithOrdersResponse,
    MarkAsShippedRequest,
    OrderDetailResponse,
    ShippingLabelInfo,
)
from app.modules.orders.services.order_service import order_service
from app.modules.tenancy.schemas.auth import UserContext

# Base router for orders
_orders_router = APIRouter(
    prefix="/orders",
    dependencies=[Depends(require_module_access("orders", FrontendType.ADMIN))],
)

# Aggregate router that includes both orders and exceptions
router = APIRouter()
logger = logging.getLogger(__name__)


# ============================================================================
# List & Statistics Endpoints
# ============================================================================


@_orders_router.get("", response_model=AdminOrderListResponse)
def get_all_orders(
    skip: int = Query(0, ge=0),
    limit: int = Query(50, ge=1, le=500),
    store_id: int | None = Query(None, description="Filter by store"),
    status: str | None = Query(None, description="Filter by status"),
    channel: str | None = Query(None, description="Filter by channel"),
    search: str | None = Query(None, description="Search by order number or customer"),
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """
    Get orders across all stores with filtering.

    Allows admins to view and filter orders across the platform.
    """
    orders, total = order_service.get_all_orders_admin(
        db=db,
        skip=skip,
        limit=limit,
        store_id=store_id,
        status=status,
        channel=channel,
        search=search,
    )

    return AdminOrderListResponse(
        orders=[AdminOrderItem(**order) for order in orders],
        total=total,
        skip=skip,
        limit=limit,
    )


@_orders_router.get("/stats", response_model=AdminOrderStats)
def get_order_stats(
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get platform-wide order statistics."""
    return order_service.get_order_stats_admin(db)


@_orders_router.get("/stores", response_model=AdminStoresWithOrdersResponse)
def get_stores_with_orders(
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get list of stores that have orders."""
    stores = order_service.get_stores_with_orders_admin(db)
    return AdminStoresWithOrdersResponse(stores=stores)


# ============================================================================
# Order Detail & Update Endpoints
# ============================================================================


@_orders_router.get("/{order_id}", response_model=OrderDetailResponse)
def get_order_detail(
    order_id: int,
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get order details including items and addresses."""
    order = order_service.get_order_by_id_admin(db, order_id)

    # Enrich with store info
    response = OrderDetailResponse.model_validate(order)
    if order.store:
        response.store_name = order.store.name
        response.store_code = order.store.store_code

    return response


@_orders_router.patch("/{order_id}/status", response_model=OrderDetailResponse)
def update_order_status(
    order_id: int,
    status_update: AdminOrderStatusUpdate,
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """
    Update order status.

    Admin can update status and add tracking number.
    Status changes are logged with optional reason.
    """
    order = order_service.update_order_status_admin(
        db=db,
        order_id=order_id,
        status=status_update.status,
        tracking_number=status_update.tracking_number,
        reason=status_update.reason,
    )

    logger.info(
        f"Admin {current_admin.email} updated order {order.order_number} "
        f"status to {status_update.status}"
    )

    db.commit()
    return order


@_orders_router.post("/{order_id}/ship", response_model=OrderDetailResponse)
def mark_order_as_shipped(
    order_id: int,
    ship_request: MarkAsShippedRequest,
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """
    Mark an order as shipped with optional tracking information.

    This endpoint:
    - Sets order status to 'shipped'
    - Sets shipped_at timestamp
    - Optionally stores tracking number, URL, and carrier
    """
    order = order_service.mark_as_shipped_admin(
        db=db,
        order_id=order_id,
        tracking_number=ship_request.tracking_number,
        tracking_url=ship_request.tracking_url,
        shipping_carrier=ship_request.shipping_carrier,
    )

    logger.info(
        f"Admin {current_admin.email} marked order {order.order_number} as shipped"
    )

    db.commit()
    return order


@_orders_router.get("/{order_id}/shipping-label", response_model=ShippingLabelInfo)
def get_shipping_label_info(
    order_id: int,
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """
    Get shipping label information for an order.

    Returns the shipment number, carrier, and generated label URL
    based on carrier settings.
    """
    return order_service.get_shipping_label_info_admin(db, order_id)


# ============================================================================
# Aggregate routers
# ============================================================================

# Import exceptions router
from app.modules.orders.routes.api.admin_exceptions import admin_exceptions_router

# Include both routers into the aggregate router
router.include_router(_orders_router, tags=["admin-orders"])
router.include_router(admin_exceptions_router, tags=["admin-order-exceptions"])
