# Where class 10 got to: two endpoints on a real database.
# Lab 5 adds the votes table, vote_count on GET /ideas, a votes list on
# GET /ideas/{id}, and POST /ideas/{id}/vote.
from fastapi import FastAPI, HTTPException
from sqlmodel import SQLModel, Field, Session, create_engine, select

class Idea(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    title: str
    body: str = ""

# The request body. Not the table class: a table=True class skips validation,
# so a POST with no title would reach the database and come back as a 500.
class IdeaCreate(SQLModel):
    title: str
    body: str = ""

engine = create_engine("sqlite:///app.db", echo=True)
SQLModel.metadata.create_all(engine)

app = FastAPI()

@app.get("/ideas")
def list_ideas():
    with Session(engine) as s:
        return s.exec(select(Idea)).all()

@app.post("/ideas", status_code=201)
def create_idea(payload: IdeaCreate):
    idea = Idea(**payload.model_dump())
    with Session(engine) as s:
        s.add(idea)
        s.commit()
        s.refresh(idea)
        return idea

@app.get("/ideas/{idea_id}")
def get_idea(idea_id: int):
    with Session(engine) as s:
        idea = s.get(Idea, idea_id)
        if idea is None:
            raise HTTPException(404, "no such idea")
        return idea
