from fastapi import APIRouter, Depends, HTTPException from typing import Annotated from ..middlewares.auth_middleware import get_current_user from ..models.users import User from ..models.words import WordSchema from ..configs.database_config import db from ..utils.response_fmt import jsonResponseFmt from bson import ObjectId import random router = APIRouter(prefix="/word", tags=["Words"]) collection = db["word"] user_dependency = Annotated[User, Depends(get_current_user)] def list_word_controlller(user): user_id = user.get("id") try: print("user_id", user_id) words = WordSchema.read_all_words_by_user_id(user_id) return words except Exception as e: raise HTTPException(status_code=500, detail=str(e)) def add_word_controller(user, word): user_id = user.get("id") try: existing_word = WordSchema.check_existing_word(word.word, user_id) if existing_word: return jsonResponseFmt(None, msg="Existed", code=400) random.shuffle(word.options) WordSchema(**word.dict()).create(user_id) return jsonResponseFmt(None, code=201) except Exception as e: return jsonResponseFmt(None, msg=str(e), code=500) def update_word_controller(user, word_id, word_data): user_id = user.get("id") try: print("user", user) print("word_id", word_id) print("word_data", word_data) word_data.user_id = user_id print("word_data", word_data.dict()) WordSchema(**word_data.dict()).update(str(word_id)) return jsonResponseFmt(None, code=200) except Exception as e: return jsonResponseFmt(None, msg=str(e), code=500) def delete_word_controller(user, word_id): user_id = user.get("id") try: existing_word = collection.find_one( {"_id": ObjectId(word_id), "user_id": user_id} ) if not existing_word: return jsonResponseFmt(None, msg="Word not found", code=404) collection.delete_one({"_id": ObjectId(word_id)}) return jsonResponseFmt(None, code=200) except Exception as e: return jsonResponseFmt(None, msg=str(e), code=500)