from fastapi import Depends, APIRouter
from sqlalchemy.orm import Session
from app import get_db
from app.api.role import crud, schemas
from libs.result_format import HttpResultResponse, HttpMessage

router = APIRouter()


@router.post("/create")
def create_user(data: schemas.RoleCreate, db: Session = Depends(get_db)):
    """添加角色"""
    db_role = crud.get_role_by_name(db, role_name=data.role_name)
    if db_role:
        return HttpResultResponse(code=400, msg=HttpMessage.ROLE_EXIST)
    res = crud.create_role(db=db, user=data)
    if not res:
        return HttpResultResponse(code=500, msg=res)
    return HttpResultResponse(data=res.id)


@router.post("/update")
def read_user(data: schemas.RoleUpdate, db: Session = Depends(get_db)):
    """角色权限分配"""
    crud.update_role(db, data)
    return HttpResultResponse()


@router.delete("/delete/{role_id}")
def delete_user(role_id: int, db: Session = Depends(get_db)):
    """角色删除"""
    res_bool = crud.delete_role(db, role_id)
    if not res_bool:
        return HttpResultResponse(code=422, msg=HttpMessage.NO_DELETE_ROLE)
    return HttpResultResponse()


@router.post("/list")
def role_list(data: schemas.RoleList, db: Session = Depends(get_db)):
    """用户列表"""
    result = crud.get_roles(db, data)
    return HttpResultResponse(count=len(result), data=result)
