from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional, Dict, Any

from app.core import get_db, get_current_active_user
from app import services
from app.schemas.order_schemas import OrderCreate, OrderUpdate, Order
from app.models.user_models import User as UserModel
from app.repositories.order_repo import get_all_orders, get_user_orders

# Роутер для заказов
order_router = APIRouter(prefix="/orders", tags=["Заказы"])

@order_router.post("/", response_model=Dict[str, Any])
async def create_order_endpoint(order: OrderCreate, current_user: UserModel = Depends(get_current_active_user), db: Session = Depends(get_db)):
    return services.create_order(db, current_user.id, order)


@order_router.get("/{order_id}", response_model=Dict[str, Any])
async def get_order_endpoint(order_id: int, current_user: UserModel = Depends(get_current_active_user), db: Session = Depends(get_db)):
    return services.get_order(db, current_user.id, order_id, current_user.is_admin)


@order_router.put("/{order_id}", response_model=Dict[str, Any])
async def update_order_endpoint(order_id: int, order: OrderUpdate, current_user: UserModel = Depends(get_current_active_user), db: Session = Depends(get_db)):
    return services.update_order(db, current_user.id, order_id, order, current_user.is_admin)


@order_router.post("/{order_id}/cancel", response_model=Dict[str, Any])
async def cancel_order_endpoint(order_id: int, current_user: UserModel = Depends(get_current_active_user), db: Session = Depends(get_db)):
    return services.cancel_order(db, current_user.id, order_id)


@order_router.get("/", response_model=List[Order])
async def get_orders(
    skip: int = 0, 
    limit: int = 100, 
    status: Optional[str] = None,
    current_user: UserModel = Depends(get_current_active_user), 
    db: Session = Depends(get_db)
):
    if current_user.is_admin:
        return get_all_orders(db, skip, limit, status)
    else:
        return get_user_orders(db, current_user.id, skip, limit) 