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

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

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

@router.post("/", response_model=schemas.TableOut)
def create_table(table: schemas.TableCreate, db: Session = Depends(get_db)):
    db_table = crud.create_table(db, table)
    return db_table
    
@router.get("/", response_model=list[schemas.TableOut])
def list_tables(db: Session = Depends(get_db)):
    return crud.get_tables(db)

@router.get("/{table_id}", response_model=schemas.TableOut)
def get_table(table_id: int, db: Session = Depends(get_db)):
    db_table = crud.get_table(db, table_id)
    if db_table is None:
        raise HTTPException(status_code=404, detail="Table not found")
    return db_table

@router.get("/by-name/{table_name}", response_model=schemas.TableOut)
def get_table_by_name(table_name: str, db: Session = Depends(get_db)):
    db_table = crud.get_table_by_name(db, table_name)
    if db_table is None:
        raise HTTPException(status_code=404, detail="Table not found")
    return db_table

@router.get("/by-number/{table_number}", response_model=schemas.TableOut)
def get_table_by_number(table_number: int, db: Session = Depends(get_db)):
    db_table = crud.get_table_by_number(db, table_number)
    if db_table is None:
        raise HTTPException(status_code=404, detail="Table not found")
    return db_table 

@router.delete("/{table_id}")
def delete_table(table_id: int, db: Session = Depends(get_db)):
    table = crud.get_table_by_id(db, table_id)
    if not table:
        raise HTTPException(status_code=404, detail="Table not found")
    crud.delete_table(db, table_id)
    return {"detail": f"Table {table_id} deleted"}