from sqlalchemy.orm import Session
from app import models, schemas
from sqlalchemy.exc import IntegrityError
from fastapi import HTTPException

def get_user(db: Session, user_id: int):
    return db.query(models.User).filter(models.User.id == user_id).first()

def get_user_by_openid_or_wxid(db: Session, identifier: str):
    return db.query(models.User).filter((models.User.openid == identifier) | (models.User.wxid == identifier)).first()

def get_users(db: Session, skip: int = 0, limit: int = 10):
    return db.query(models.User).offset(skip).limit(limit).all()

def create_user(db: Session, user: schemas.UserCreate):
    db_user = models.User(**user.dict())
    try:
        db.add(db_user)
        db.commit()
        db.refresh(db_user)
    except IntegrityError:
        db.rollback()
        # wxid的唯一性
        raise HTTPException(status_code=400, detail="wxid must be unique")
    return db_user

def delete_user(db: Session, user: models.User):
    db.delete(user)
    db.commit()
    return user

# def update_user(db: Session, user: models.User, user_update: schemas.UserUpdate):
#     for key, value in user_update.dict(exclude_unset=True).items():
#         setattr(user, key, value)
#     db.commit()
#     db.refresh(user)
#     return user
def update_user(db: Session, user: models.User, user_update: schemas.UserUpdate):
    for var, value in vars(user_update).items():
        if value is not None:
            setattr(user, var, value)
    db.commit()
    db.refresh(user)
    return user