from datetime import datetime, timezone
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlmodel import Session, select
from app.database import get_session
from app.models.task import Task, TaskCreate

router = APIRouter(tags=["tâches"])


@router.get("/tasks", response_model=List[Task])
def list_tasks(
    statut: Optional[str] = None,
    garden_id: Optional[int] = None,
    session: Session = Depends(get_session),
):
    q = select(Task)
    if statut:
        q = q.where(Task.statut == statut)
    if garden_id:
        q = q.where(Task.garden_id == garden_id)
    return session.exec(q).all()


@router.post("/tasks", response_model=Task, status_code=status.HTTP_201_CREATED)
def create_task(data: TaskCreate, session: Session = Depends(get_session)):
    t = Task(**data.model_dump())
    session.add(t)
    session.commit()
    session.refresh(t)
    return t


@router.get("/tasks/{id}", response_model=Task)
def get_task(id: int, session: Session = Depends(get_session)):
    t = session.get(Task, id)
    if not t:
        raise HTTPException(status_code=404, detail="Tâche introuvable")
    return t


@router.put("/tasks/{id}", response_model=Task)
def update_task(id: int, data: TaskCreate, session: Session = Depends(get_session)):
    t = session.get(Task, id)
    if not t:
        raise HTTPException(status_code=404, detail="Tâche introuvable")
    for k, v in data.model_dump(exclude_unset=True).items():
        setattr(t, k, v)
    t.updated_at = datetime.now(timezone.utc)
    session.add(t)
    session.commit()
    session.refresh(t)
    return t


@router.put("/tasks/{id}/statut", response_model=Task)
def update_statut(id: int, statut: str, session: Session = Depends(get_session)):
    t = session.get(Task, id)
    if not t:
        raise HTTPException(status_code=404, detail="Tâche introuvable")
    t.statut = statut
    t.updated_at = datetime.now(timezone.utc)
    session.add(t)
    session.commit()
    session.refresh(t)
    return t


@router.delete("/tasks/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_task(id: int, session: Session = Depends(get_session)):
    t = session.get(Task, id)
    if not t:
        raise HTTPException(status_code=404, detail="Tâche introuvable")
    session.delete(t)
    session.commit()
