"""用户认证"""
import hashlib
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.database import get_db
from app.models import User
from app.auth_middleware import create_token, require_auth, ROLES

router = APIRouter(prefix="/api/cma/auth", tags=["认证"])


@router.post("/login")
def login(data: dict, db: Session = Depends(get_db)):
    username = data.get("username", "")
    password = data.get("password", "")
    user = db.query(User).filter(User.username == username).first()
    if not user or user.password_hash != hashlib.sha256(password.encode()).hexdigest():
        raise HTTPException(401, "用户名或密码错误")

    token = create_token(user.id)
    return {
        "token": token,
        "user": {
            "id": user.id,
            "username": user.username,
            "name": user.name,
            "role": user.role,
            "role_name": ROLES.get(user.role, {}).get("name", user.role),
        }
    }


@router.post("/register")
def register(data: dict, db: Session = Depends(get_db)):
    exist = db.query(User).filter(User.username == data.get("username")).first()
    if exist:
        raise HTTPException(400, "用户名已存在")
    user = User(
        username=data["username"],
        password_hash=hashlib.sha256(data["password"].encode()).hexdigest(),
        name=data.get("name", data["username"]),
        role=data.get("role", "business"),
    )
    db.add(user)
    db.commit()
    return {"message": "注册成功"}


@router.get("/me")
def get_me(current_user: User = Depends(require_auth)):
    """获取当前用户信息"""
    return {
        "id": current_user.id,
        "username": current_user.username,
        "name": current_user.name,
        "role": current_user.role,
        "role_name": ROLES.get(current_user.role, {}).get("name", current_user.role),
        "phone": current_user.phone,
    }


@router.get("/roles")
def list_roles():
    """返回角色列表（给前端用）"""
    return {
        "data": [
            {"code": k, "name": v["name"], "priority": v["priority"]}
            for k, v in ROLES.items()
        ]
    }
