# backend/app/routes/tournaments/tournaments.py
from fastapi import Depends, HTTPException
from sqlalchemy.orm import Session

from ... import crud, schemas
from ...constants import SUCCESS
from ...core.websocket_manager import send_ws_update
from ...database import get_db
from ...core.auth import get_admin_user
from . import router


@router.post("", response_model=schemas.TournamentSettingsResponse)
async def create_tournament(
    data: schemas.TournamentCreate,
    db: Session = Depends(get_db),
    user: dict = Depends(get_admin_user),
):
    new_t = crud.create_tournament(db, data)
    await send_ws_update(new_t.id)
    return new_t


@router.get("", response_model=list[schemas.TournamentOut])
def list_tournaments(db: Session = Depends(get_db)):
    return crud.get_tournaments(db)


@router.get("/{id}", response_model=schemas.TournamentDetail)
def get_tournament(id: str, db: Session = Depends(get_db)):
    t = crud.get_tournament(db, id)
    if not t:
        raise HTTPException(404, "Tournament not found")
    return t


@router.patch("/{id}", response_model=schemas.TournamentSettingsResponse)
async def update_settings(
    id: str,
    data: schemas.TournamentUpdate,
    db: Session = Depends(get_db),
    user: dict = Depends(get_admin_user),
):
    t = crud.update_tournament_details(db, id, data)
    if not t:
        raise HTTPException(404, "Not found")

    await send_ws_update(id)
    return t


@router.delete("/{id}")
async def delete_tournament(
    id: str, db: Session = Depends(get_db), user: dict = Depends(get_admin_user)
):
    success = crud.delete_tournament(db, id)
    if not success:
        raise HTTPException(404, "Tournament not found")

    await send_ws_update(id)

    return SUCCESS


@router.patch("/{id}/courts", response_model=schemas.TournamentOut)
def update_tournament_courts(
    id: str,
    court_ids: list[int],
    db: Session = Depends(get_db),
    user: dict = Depends(get_admin_user),
):
    """Updates the global courts assigned to a specific tournament"""
    t = crud.update_tournament_courts(db, id, court_ids)
    if not t:
        raise HTTPException(404, "Tournament not found")
    return t
