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

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

@admin_api_bp.route("/feedbacks", methods=["GET"])
@admin_required
def get_all_feedbacks():
    """管理员获取所有反馈"""
    status = request.args.get("status")
    try:
        limit = int(request.args.get("limit", 100))
        offset = int(request.args.get("offset", 0))
        limit = min(max(1, limit), 1000)
        offset = max(0, offset)
    except (ValueError, TypeError):
        return jsonify({"error": "无效的分页参数"}), 400

    feedbacks = database.get_bug_feedbacks(limit=limit, offset=offset, status_filter=status)
    stats = database.get_feedback_stats()
    return jsonify({"feedbacks": feedbacks, "stats": stats})


@admin_api_bp.route("/feedbacks/<int:feedback_id>/reply", methods=["POST"])
@admin_required
def reply_to_feedback(feedback_id):
    """管理员回复反馈"""
    data = request.get_json() or {}
    reply = (data.get("reply") or "").strip()

    if not reply:
        return jsonify({"error": "回复内容不能为空"}), 400

    if database.reply_feedback(feedback_id, reply):
        return jsonify({"message": "回复成功"})
    return jsonify({"error": "反馈不存在"}), 404


@admin_api_bp.route("/feedbacks/<int:feedback_id>/close", methods=["POST"])
@admin_required
def close_feedback_api(feedback_id):
    """管理员关闭反馈"""
    if database.close_feedback(feedback_id):
        return jsonify({"message": "已关闭"})
    return jsonify({"error": "反馈不存在"}), 404


@admin_api_bp.route("/feedbacks/<int:feedback_id>", methods=["DELETE"])
@admin_required
def delete_feedback_api(feedback_id):
    """管理员删除反馈"""
    if database.delete_feedback(feedback_id):
        return jsonify({"message": "已删除"})
    return jsonify({"error": "反馈不存在"}), 404
