from typing import List

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

from app.core.entities.calculate_total_order_request import CalculateTotalOrderRequest
from app.core.usecases.auth_service import verify_token
from app.core.usecases.new_total_order_service import NewTotalOrderService
from app.infrastructure.database.dependencies import get_db
from app.core.entities.total_order import TotalOrderEntity
from app.core.usecases.total_order_service import TotalOrdersService
from app.infrastructure.database.models.users import User

router = APIRouter()


@router.get("/total-orders", response_model=List[TotalOrderEntity])
def read_total_orders(db: Session = Depends(get_db),
                      current_user: User = Depends(verify_token)):
    service = TotalOrdersService(db)
    return service.get_all_total_orders()


@router.get("/total-orders/{total_order_id}", response_model=TotalOrderEntity)
def read_total_order(total_order_id: int, db: Session = Depends(get_db),
                     current_user: User = Depends(verify_token)):
    service = TotalOrdersService(db)
    total_order = service.get_total_order_by_id(total_order_id)
    if total_order is None:
        raise HTTPException(status_code=404, detail="Total order not found")
    return total_order


@router.post("/total-orders", response_model=TotalOrderEntity)
def create_total_order(total_order: TotalOrderEntity, db: Session = Depends(get_db),
                       current_user: User = Depends(verify_token)):
    service = TotalOrdersService(db)
    return service.create_total_order(total_order)


@router.put("/total-orders/{total_order_id}", response_model=TotalOrderEntity)
def update_total_order(total_order_id: int, total_order: TotalOrderEntity, db: Session = Depends(get_db),
                       current_user: User = Depends(verify_token)):
    service = TotalOrdersService(db)
    updated_total_order = service.update_total_order(total_order_id, total_order)
    if updated_total_order is None:
        raise HTTPException(status_code=404, detail="Total order not found")
    return updated_total_order


@router.delete("/total-orders/{total_order_id}", response_model=bool)
def delete_total_order(total_order_id: int, db: Session = Depends(get_db),
                       current_user: User = Depends(verify_token)):
    service = TotalOrdersService(db)
    success = service.delete_total_order(total_order_id)
    if not success:
        raise HTTPException(status_code=404, detail="Total order not found")
    return success


@router.post("/total-orders/calculate")
def calculate_total_order(
    request: CalculateTotalOrderRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(verify_token)
):
    service = NewTotalOrderService(db)
    service.total_calculate(current_user, request.deadline, request.robotsCount)
    return {"status": "OK"}