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.recolte import Observation, ObservationCreate, Recolte, RecolteCreate

router = APIRouter(tags=["récoltes"])


# ── Récoltes (nested sous plantings) ──────────────────────────────────────────

@router.get("/plantings/{planting_id}/recoltes", response_model=List[Recolte])
def list_recoltes(planting_id: int, session: Session = Depends(get_session)):
    return session.exec(
        select(Recolte).where(Recolte.plantation_id == planting_id)
    ).all()


@router.post(
    "/plantings/{planting_id}/recoltes",
    response_model=Recolte,
    status_code=status.HTTP_201_CREATED,
)
def create_recolte(
    planting_id: int,
    data: RecolteCreate,
    session: Session = Depends(get_session),
):
    r = Recolte(plantation_id=planting_id, **data.model_dump())
    session.add(r)
    session.commit()
    session.refresh(r)
    return r


@router.delete("/recoltes/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_recolte(id: int, session: Session = Depends(get_session)):
    r = session.get(Recolte, id)
    if not r:
        raise HTTPException(404, "Récolte introuvable")
    session.delete(r)
    session.commit()


# ── Observations ───────────────────────────────────────────────────────────────

@router.get("/observations", response_model=List[Observation])
def list_observations(
    plantation_id: Optional[int] = Query(None),
    garden_id: Optional[int] = Query(None),
    session: Session = Depends(get_session),
):
    q = select(Observation)
    if plantation_id is not None:
        q = q.where(Observation.plantation_id == plantation_id)
    if garden_id is not None:
        q = q.where(Observation.garden_id == garden_id)
    return session.exec(q).all()


@router.post("/observations", response_model=Observation, status_code=status.HTTP_201_CREATED)
def create_observation(data: ObservationCreate, session: Session = Depends(get_session)):
    o = Observation(**data.model_dump())
    session.add(o)
    session.commit()
    session.refresh(o)
    return o


@router.get("/observations/{id}", response_model=Observation)
def get_observation(id: int, session: Session = Depends(get_session)):
    o = session.get(Observation, id)
    if not o:
        raise HTTPException(404, "Observation introuvable")
    return o


@router.delete("/observations/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_observation(id: int, session: Session = Depends(get_session)):
    o = session.get(Observation, id)
    if not o:
        raise HTTPException(404, "Observation introuvable")
    session.delete(o)
    session.commit()
