from typing import List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlmodel import Session, select
from database import get_session
from models import Venue
from schemas import VenueCreate, VenueRead, VenueUpdate
from auth import get_current_user

router = APIRouter(prefix="/venues", tags=["venues"])

@router.post("/", response_model=VenueRead)
def create_venue(venue: VenueCreate, session: Session = Depends(get_session), current_user = Depends(get_current_user)):
    db_venue = Venue.model_validate(venue)
    session.add(db_venue)
    session.commit()
    session.refresh(db_venue)
    return db_venue

@router.get("/", response_model=List[VenueRead])
def read_venues(offset: int = 0, limit: int = Query(default=1000, le=1000), session: Session = Depends(get_session)):
    venues = session.exec(select(Venue).offset(offset).limit(limit)).all()
    return venues

@router.get("/{slug}", response_model=VenueRead)
def read_venue(slug: str, session: Session = Depends(get_session)):
    venue = session.exec(select(Venue).where(Venue.slug == slug)).first()
    
    if not venue:
        raise HTTPException(status_code=404, detail="Venue not found")
    return venue

@router.patch("/{venue_id}", response_model=VenueRead)
def update_venue(venue_id: int, venue: VenueUpdate, session: Session = Depends(get_session), current_user = Depends(get_current_user)):
    db_venue = session.get(Venue, venue_id)
    if not db_venue:
        raise HTTPException(status_code=404, detail="Venue not found")
    venue_data = venue.model_dump(exclude_unset=True)
    db_venue.sqlmodel_update(venue_data)
    session.add(db_venue)
    session.commit()
    session.refresh(db_venue)
    return db_venue
