from flask import Blueprint, request
from flask_jwt_extended import 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


user_bp = Blueprint("user", __name__)


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


@user_bp.put("/profile")
@jwt_required()
def update_profile():
    user = current_user()
    if not user:
        return fail("用户不存在", 404)

    payload = request.get_json(silent=True) or {}
    if "nickname" in payload:
        user.nickname = (payload.get("nickname") or user.nickname).strip() or user.nickname
    if "company" in payload:
        user.company = (payload.get("company") or "").strip()
    if "title" in payload:
        user.title = (payload.get("title") or "").strip()
    if "phone" in payload:
        user.phone = (payload.get("phone") or "").strip()

    new_password = payload.get("password")
    if new_password:
        if len(new_password) < 6:
            return fail("新密码至少6位", 400)
        user.set_password(new_password)

    db.session.commit()
    return ok(user.to_dict(), "个人信息更新成功")


@user_bp.get("/search")
@jwt_required()
def search_users():
    keyword = (request.args.get("keyword") or "").strip()
    if not keyword:
        return ok([])

    users = (
        User.query.filter(User.username.like(f"%{keyword}%") | User.nickname.like(f"%{keyword}%"))
        .order_by(User.id.desc())
        .limit(20)
        .all()
    )
    return ok([item.to_dict() for item in users])
