from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlmodel import Session, select
from app.database import get_session
from app.models.tool import Tool

router = APIRouter(tags=["outils"])


@router.get("/tools", response_model=List[Tool])
def list_tools(
    categorie: Optional[str] = Query(None),
    session: Session = Depends(get_session),
):
    q = select(Tool)
    if categorie:
        q = q.where(Tool.categorie == categorie)
    return session.exec(q).all()


@router.post("/tools", response_model=Tool, status_code=status.HTTP_201_CREATED)
def create_tool(t: Tool, session: Session = Depends(get_session)):
    session.add(t)
    session.commit()
    session.refresh(t)
    return t


@router.get("/tools/{id}", response_model=Tool)
def get_tool(id: int, session: Session = Depends(get_session)):
    t = session.get(Tool, id)
    if not t:
        raise HTTPException(404, "Outil introuvable")
    return t


@router.put("/tools/{id}", response_model=Tool)
def update_tool(id: int, data: Tool, session: Session = Depends(get_session)):
    t = session.get(Tool, id)
    if not t:
        raise HTTPException(404, "Outil introuvable")
    for k, v in data.model_dump(exclude_unset=True, exclude={"id", "created_at"}).items():
        setattr(t, k, v)
    session.add(t)
    session.commit()
    session.refresh(t)
    return t


@router.delete("/tools/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_tool(id: int, session: Session = Depends(get_session)):
    t = session.get(Tool, id)
    if not t:
        raise HTTPException(404, "Outil introuvable")
    session.delete(t)
    session.commit()
