from datetime import datetime, timezone
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlmodel import Session, select
from app.database import get_session
from app.models.planting import Planting, PlantingCreate, PlantingEvent

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


@router.get("/plantings", response_model=List[Planting])
def list_plantings(session: Session = Depends(get_session)):
    return session.exec(select(Planting)).all()


@router.post("/plantings", response_model=Planting, status_code=status.HTTP_201_CREATED)
def create_planting(data: PlantingCreate, session: Session = Depends(get_session)):
    p = Planting(**data.model_dump())
    session.add(p)
    session.commit()
    session.refresh(p)
    return p


@router.get("/plantings/{id}", response_model=Planting)
def get_planting(id: int, session: Session = Depends(get_session)):
    p = session.get(Planting, id)
    if not p:
        raise HTTPException(status_code=404, detail="Plantation introuvable")
    return p


@router.put("/plantings/{id}", response_model=Planting)
def update_planting(id: int, data: PlantingCreate, session: Session = Depends(get_session)):
    p = session.get(Planting, id)
    if not p:
        raise HTTPException(status_code=404, detail="Plantation introuvable")
    for k, v in data.model_dump(exclude_unset=True).items():
        setattr(p, k, v)
    p.updated_at = datetime.now(timezone.utc)
    session.add(p)
    session.commit()
    session.refresh(p)
    return p


@router.delete("/plantings/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_planting(id: int, session: Session = Depends(get_session)):
    p = session.get(Planting, id)
    if not p:
        raise HTTPException(status_code=404, detail="Plantation introuvable")
    session.delete(p)
    session.commit()


@router.get("/plantings/{id}/events", response_model=List[PlantingEvent])
def list_events(id: int, session: Session = Depends(get_session)):
    return session.exec(select(PlantingEvent).where(PlantingEvent.planting_id == id)).all()


@router.post("/plantings/{id}/events", response_model=PlantingEvent, status_code=status.HTTP_201_CREATED)
def create_event(id: int, e: PlantingEvent, session: Session = Depends(get_session)):
    e.planting_id = id
    session.add(e)
    session.commit()
    session.refresh(e)
    return e
