from typing import List
from fastapi import Depends, APIRouter, HTTPException, FastAPI
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

import models
from app.api.users import crud, schemas
from core.storage.db import SessionLocal

router = APIRouter()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# @router.post("/", response_model=schemas.User)
# def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
#     db_user = crud.get_user_by_email(db, email=user.email)
#     if db_user:
#         raise HTTPException(status_code=400, detail="Email already registered")
#     return crud.create_user(db=db, user=user)


@router.get("/", response_model=List[schemas.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = crud.get_users(db, skip=skip, limit=limit)
    return users


@router.get("/{user_id}", response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = crud.get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user


@router.post("/login", tags=["POST"])
def login():
    """
    OAuth2 compatible token login, get an access token for future requests.
    """
    # bucket = get_default_bucket()
    # user = crud.user.authenticate(
    #     bucket, username=form_data.username, password=form_data.password
    # )

    # if not user:
    #     raise HTTPException(status_code=400, detail="Incorrect email or password")
    # elif not crud.user.is_active(user):
    #     raise HTTPException(status_code=400, detail="Inactive user")
    # access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
    return {

        "token_type": "bearer",
    }


@router.post("/create", response_model=schemas.User)
def create_user(data: schemas.UserCreate, db: Session = Depends(get_db)):
    """添加用户"""
    db_user = crud.get_user_by_name(db, username=data.username)
    if db_user:
        raise HTTPException(status_code=400, detail="用户已存在")
    return crud.create_user(db=db, user=data)

