from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app import schemas, crud, database
from typing import List

router = APIRouter(prefix="/orders", tags=["orders"])

def get_db():
    db = database.SessionLocal()
    try:
        yield db
    finally:
        db.close()

@router.post("/", response_model=schemas.OrderOut)
def create_order(order: schemas.OrderCreate, db: Session = Depends(get_db)):
    db_order = crud.create_order(db, order)
    return db_order

@router.get("/", response_model=List[schemas.OrderOut])
def list_orders(db: Session = Depends(get_db)):
    return crud.get_orders(db)

@router.get("/{order_id}", response_model=schemas.OrderOut)
def get_order(order_id: int, db: Session = Depends(get_db)):
    db_order = crud.get_order(db, order_id)
    if db_order is None:
        raise HTTPException(status_code=404, detail="Order not found")
    return db_order

@router.get("/pending/", response_model=List[schemas.OrderOut])
def get_pending_by_older(db: Session = Depends(get_db)):
    return crud.get_pending_orders(db)

@router.post("/{order_id}/status", response_model=schemas.OrderOut)
def update_order_status(order_id: int, db: Session = Depends(get_db)):
    db_order = crud.next_order_status(db, crud.get_order(db, order_id))
    if db_order is None:
        raise HTTPException(status_code=404, detail="Order not found")
    return db_order

# Nuevo endpoint para eliminar una orden por su id
@router.delete("/{order_id}")
def delete_order(order_id: int, db: Session = Depends(get_db)):
    db_order = crud.get_order(db, order_id)
    if db_order is None:
        raise HTTPException(status_code=404, detail="Order not found")
    db.delete(db_order)
    db.commit()
    return {"detail": f"Order {order_id} deleted"}