from fastapi import APIRouter, HTTPException, Depends, status
from fastapi.security import OAuth2PasswordRequestForm
from ..models import User, UserInDB
from ..database import get_db
from ..auth import get_password_hash, verify_password, create_access_token, oauth2_scheme
from bson import ObjectId
from typing import List

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


def get_user(username: str):
  db = get_db()
  user_dict = db.users.find_one({"username": username})
  if user_dict:
    return UserInDB(**user_dict)


async def get_current_user(token: str = Depends(oauth2_scheme)):
  credentials_exception = HTTPException(
      status_code=status.HTTP_401_UNAUTHORIZED,
      detail="Could not validate credentials",
      headers={"WWW-Authenticate": "Bearer"},
  )
  # Implement JWT token validation here
  # For brevity, we're skipping the actual implementation
  username = "test_user"  # This should come from the validated token
  user = get_user(username)
  if user is None:
    raise credentials_exception
  return user


@router.post("/register", response_model=User)
async def create_user(user: UserInDB):
  db = get_db()
  existing_user = db.users.find_one({"username": user.username})
  if existing_user:
    raise HTTPException(status_code=400, detail="Username already registered")
  hashed_password = get_password_hash(user.password)
  user_dict = user.dict()
  user_dict["hashed_password"] = hashed_password
  del user_dict["password"]
  result = db.users.insert_one(user_dict)
  created_user = db.users.find_one({"_id": result.inserted_id})
  return User(**created_user)


@router.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
  user = get_user(form_data.username)
  if not user or not verify_password(form_data.password, user.hashed_password):
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Incorrect username or password",
        headers={"WWW-Authenticate": "Bearer"},
    )
  access_token = create_access_token(data={"sub": user.username})
  return {"access_token": access_token, "token_type": "bearer"}


@router.get("/me", response_model=User)
async def read_users_me(current_user: User = Depends(get_current_user)):
  return current_user


@router.get("/", response_model=List[User])
async def read_users(skip: int = 0, limit: int = 10, current_user: User = Depends(get_current_user)):
  db = get_db()
  users = list(db.users.find().skip(skip).limit(limit))
  return [User(**user) for user in users]


@router.put("/{user_id}", response_model=User)
async def update_user(user_id: str, user: UserInDB, current_user: User = Depends(get_current_user)):
  db = get_db()
  existing_user = db.users.find_one({"_id": ObjectId(user_id)})
  if not existing_user:
    raise HTTPException(status_code=404, detail="User not found")
  update_data = user.dict(exclude_unset=True)
  if "password" in update_data:
    update_data["hashed_password"] = get_password_hash(update_data["password"])
    del update_data["password"]
  result = db.users.update_one(
      {"_id": ObjectId(user_id)}, {"$set": update_data})
  if result.modified_count == 1:
    updated_user = db.users.find_one({"_id": ObjectId(user_id)})
    return User(**updated_user)
  else:
    raise HTTPException(status_code=400, detail="User update failed")


@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_user(user_id: str, current_user: User = Depends(get_current_user)):
  db = get_db()
  result = db.users.delete_one({"_id": ObjectId(user_id)})
  if result.deleted_count != 1:
    raise HTTPException(status_code=404, detail="User not found")
