#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations

import database
from app_security import validate_password
from flask import jsonify, request, session
from routes.admin_api import admin_api_bp
from routes.decorators import admin_required

# ==================== 密码重置 / 反馈（管理员） ====================


@admin_api_bp.route("/admin/password", methods=["PUT"])
@admin_required
def update_admin_password():
    """修改管理员密码（要求提供当前密码并校验新密码强度）"""
    data = request.json or {}
    current_password = (data.get("current_password") or "").strip()
    new_password = (data.get("new_password") or "").strip()

    if not current_password:
        return jsonify({"error": "当前密码不能为空"}), 400

    if not new_password:
        return jsonify({"error": "新密码不能为空"}), 400

    if current_password == new_password:
        return jsonify({"error": "新密码不能与当前密码相同"}), 400

    is_valid, error_msg = validate_password(new_password)
    if not is_valid:
        return jsonify({"error": error_msg}), 400

    username = session.get("admin_username")
    if not username:
        return jsonify({"error": "未登录"}), 401

    admin = database.verify_admin(username, current_password)
    if not admin:
        return jsonify({"error": "当前密码错误"}), 401

    if database.update_admin_password(username, new_password):
        session["admin_reauth_until"] = 0
        session.modified = True
        return jsonify({"success": True})
    return jsonify({"error": "修改失败"}), 400


@admin_api_bp.route("/admin/username", methods=["PUT"])
@admin_required
def update_admin_username():
    """修改管理员用户名"""
    data = request.json or {}
    new_username = (data.get("new_username") or "").strip()

    if not new_username:
        return jsonify({"error": "用户名不能为空"}), 400

    old_username = session.get("admin_username")
    if database.update_admin_username(old_username, new_username):
        session["admin_username"] = new_username
        return jsonify({"success": True})
    return jsonify({"error": "修改失败，用户名可能已存在"}), 400


@admin_api_bp.route("/users/<int:user_id>/reset_password", methods=["POST"])
@admin_required
def admin_reset_password_route(user_id):
    """管理员直接重置用户密码（无需审核）"""
    data = request.json or {}
    new_password = (data.get("new_password") or "").strip()

    if not new_password:
        return jsonify({"error": "新密码不能为空"}), 400

    is_valid, error_msg = validate_password(new_password)
    if not is_valid:
        return jsonify({"error": error_msg}), 400

    if database.admin_reset_user_password(user_id, new_password):
        return jsonify({"message": "密码重置成功"})
    return jsonify({"error": "重置失败，用户不存在"}), 400
