from typing import List, Optional

from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.database import get_db
from app.enums.enums import OrderStatusEnum
from app.schemas.user.order_schemas import (
    OrderRefundRequest,
    OrderRefundResponse,
    OrderResponse,
    OrderStatusUpdateRequest,
)
from app.schemas.staff.dashboard_schemas import ChainOverviewResponse
from app.services.user.order_service import OrderService
from app.services.staff.dashboard_service import DashboardService
from app.utils.auth import get_admin_user, get_current_chain_id


router = APIRouter()


@router.get(
    "",
    response_model=List[OrderResponse],
    summary="List orders"
)
async def list_orders(
    status_filter: Optional[OrderStatusEnum] = Query(
        None,
        description="Filter orders by status"
    ),
    current_admin: dict = Depends(get_admin_user),
    db: AsyncSession = Depends(get_db)
):
    service = OrderService(db)
    return await service.list_orders(status_filter=status_filter)


@router.get(
    "/{order_id}",
    response_model=OrderResponse,
    summary="Get order details"
)
async def get_order(
    order_id: int,
    current_admin: dict = Depends(get_admin_user),
    db: AsyncSession = Depends(get_db)
):
    service = OrderService(db)
    return await service.get_order(order_id)


@router.put(
    "/{order_id}/status",
    response_model=OrderResponse,
    summary="Update order status"
)
async def update_order_status(
    order_id: int,
    status_update: OrderStatusUpdateRequest,
    current_admin: dict = Depends(get_admin_user),
    db: AsyncSession = Depends(get_db)
):
    service = OrderService(db)
    return await service.update_order_status(order_id, status_update.status)


@router.get(
    "/chain/overview",
    response_model=ChainOverviewResponse,
    summary="Get chain overview statistics (Admin only)"
)
async def get_chain_overview(
    current_admin: dict = Depends(get_admin_user),
    chain_id: int = Depends(get_current_chain_id),
    db: AsyncSession = Depends(get_db)
):
    """
    Get overview statistics for the admin's chain including:
    - Total number of stores
    - Total number of orders
    - Total sales (sum of final_amount from completed orders)
    - Orders by status
    - Average order value
    """
    service = DashboardService(db)
    return await service.get_chain_overview(chain_id)


@router.get(
    "/chain/all",
    response_model=List[OrderResponse],
    summary="Get all orders for the chain (Admin only)"
)
async def get_chain_orders(
    status_filter: Optional[OrderStatusEnum] = Query(
        None,
        description="Filter orders by status"
    ),
    skip: int = Query(0, ge=0, description="Number of records to skip"),
    limit: int = Query(100, ge=1, le=100, description="Maximum number of records to return"),
    current_admin: dict = Depends(get_admin_user),
    chain_id: int = Depends(get_current_chain_id),
    db: AsyncSession = Depends(get_db)
):
    """
    Get all orders from all stores in the admin's chain.
    Supports pagination and status filtering.
    """
    service = OrderService(db)
    return await service.get_chain_orders(chain_id, status_filter, skip, limit)


@router.post(
    "/{order_id}/refund",
    response_model=OrderRefundResponse,
    summary="Refund an order (Admin only)"
)
async def refund_order(
    order_id: int,
    refund_request: Optional[OrderRefundRequest] = None,
    current_admin: dict = Depends(get_admin_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Refund an order via Stripe. 
    Refunds the full amount (including taxes) back to the user's card.
    Any Stripe charges will be refunded to the user.
    Only accessible by admin.
    """
    service = OrderService(db)
    return await service.refund_order(order_id, refund_request)

