from typing import List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlmodel import Session, select, func
from database import get_session
from models import Tour, Show, User
from schemas import TourCreate, TourRead, TourUpdate
from auth import get_current_user

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

@router.post("/", response_model=TourRead)
def create_tour(
    tour: TourCreate, 
    session: Session = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    db_tour = Tour.model_validate(tour)
    session.add(db_tour)
    session.commit()
    session.refresh(db_tour)
    return db_tour

@router.get("/")
def read_tours(
    offset: int = 0, 
    limit: int = Query(default=100, le=500), 
    session: Session = Depends(get_session)
):
    """Get all tours with show counts"""
    tours = session.exec(select(Tour).offset(offset).limit(limit)).all()
    
    # Get show counts per tour
    result = []
    for tour in tours:
        show_count = session.exec(
            select(func.count(Show.id)).where(Show.tour_id == tour.id)
        ).one()
        tour_dict = tour.model_dump()
        tour_dict["show_count"] = show_count
        result.append(tour_dict)
    
    return result

@router.get("/{slug}")
def read_tour(slug: str, session: Session = Depends(get_session)):
    """Get tour by slug or ID"""
    # Try as ID first (for backwards compatibility)
    try:
        tour_id = int(slug)
        tour = session.get(Tour, tour_id)
    except ValueError:
        tour = session.exec(select(Tour).where(Tour.slug == slug)).first()
    
    if not tour:
        raise HTTPException(status_code=404, detail="Tour not found")
    
    # Add show count
    show_count = session.exec(
        select(func.count(Show.id)).where(Show.tour_id == tour.id)
    ).one()
    tour_dict = tour.model_dump()
    tour_dict["show_count"] = show_count
    
    return tour_dict

