# app/api/v1/vendor/orders.py
"""
Vendor order management endpoints.

Vendor Context: Uses token_vendor_id from JWT token (authenticated vendor API pattern).
The get_current_vendor_api dependency guarantees token_vendor_id is present.
"""

import logging

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

from app.api.deps import get_current_vendor_api
from app.core.database import get_db
from app.services.order_service import order_service
from models.database.user import User
from models.schema.order import (
    OrderDetailResponse,
    OrderListResponse,
    OrderResponse,
    OrderUpdate,
)

router = APIRouter(prefix="/orders")
logger = logging.getLogger(__name__)


@router.get("", response_model=OrderListResponse)
def get_vendor_orders(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    status: str | None = Query(None, description="Filter by order status"),
    customer_id: int | None = Query(None, description="Filter by customer"),
    current_user: User = Depends(get_current_vendor_api),
    db: Session = Depends(get_db),
):
    """
    Get all orders for vendor.

    Supports filtering by:
    - status: Order status (pending, processing, shipped, delivered, cancelled)
    - customer_id: Filter orders from specific customer

    Vendor is determined from JWT token (vendor_id claim).
    Requires Authorization header (API endpoint).
    """
    orders, total = order_service.get_vendor_orders(
        db=db,
        vendor_id=current_user.token_vendor_id,
        skip=skip,
        limit=limit,
        status=status,
        customer_id=customer_id,
    )

    return OrderListResponse(
        orders=[OrderResponse.model_validate(o) for o in orders],
        total=total,
        skip=skip,
        limit=limit,
    )


@router.get("/{order_id}", response_model=OrderDetailResponse)
def get_order_details(
    order_id: int,
    current_user: User = Depends(get_current_vendor_api),
    db: Session = Depends(get_db),
):
    """
    Get detailed order information including items and addresses.

    Requires Authorization header (API endpoint).
    """
    order = order_service.get_order(
        db=db, vendor_id=current_user.token_vendor_id, order_id=order_id
    )

    return OrderDetailResponse.model_validate(order)


@router.put("/{order_id}/status", response_model=OrderResponse)
def update_order_status(
    order_id: int,
    order_update: OrderUpdate,
    current_user: User = Depends(get_current_vendor_api),
    db: Session = Depends(get_db),
):
    """
    Update order status and tracking information.

    Valid statuses:
    - pending: Order placed, awaiting processing
    - processing: Order being prepared
    - shipped: Order shipped to customer
    - delivered: Order delivered
    - cancelled: Order cancelled
    - refunded: Order refunded

    Requires Authorization header (API endpoint).
    """
    order = order_service.update_order_status(
        db=db,
        vendor_id=current_user.token_vendor_id,
        order_id=order_id,
        order_update=order_update,
    )
    db.commit()

    logger.info(
        f"Order {order.order_number} status updated to {order.status} "
        f"by user {current_user.username}"
    )

    return OrderResponse.model_validate(order)
