from flask import Blueprint, request
from flask_jwt_extended import create_access_token, jwt_required

from app.extensions import db
from app.models import User
from app.utils.auth import current_user
from app.utils.response import fail, ok


auth_bp = Blueprint("auth", __name__)


@auth_bp.post("/register")
def register():
    payload = request.get_json(silent=True) or {}
    username = (payload.get("username") or "").strip()
    password = payload.get("password") or ""
    nickname = (payload.get("nickname") or username).strip()

    if len(username) < 3:
        return fail("用户名至少3位", 400)
    if len(password) < 6:
        return fail("密码至少6位", 400)
    if User.query.filter_by(username=username).first():
        return fail("用户名已存在", 409)

    user = User(
        username=username,
        nickname=nickname or username,
        company=(payload.get("company") or "").strip(),
        title=(payload.get("title") or "").strip(),
        phone=(payload.get("phone") or "").strip(),
        is_admin=bool(payload.get("is_admin", False)),
    )
    user.set_password(password)

    db.session.add(user)
    db.session.commit()

    return ok(user.to_dict(), "注册成功")


@auth_bp.post("/login")
def login():
    payload = request.get_json(silent=True) or {}
    username = (payload.get("username") or "").strip()
    password = payload.get("password") or ""

    user = User.query.filter_by(username=username).first()
    if not user or not user.check_password(password):
        return fail("用户名或密码错误", 401)

    access_token = create_access_token(
        identity=str(user.id),
        additional_claims={"is_admin": bool(user.is_admin), "username": user.username},
    )

    return ok({"token": access_token, "user": user.to_dict()}, "登录成功")


@auth_bp.get("/me")
@jwt_required()
def me():
    user = current_user()
    if not user:
        return fail("用户不存在", 404)
    return ok(user.to_dict())
