from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required
from models.subscription import Subscription

admin_subscription_bp = Blueprint("admin_subscription", __name__, url_prefix="/admin/subscriptions")

# List all subscriptions
@admin_subscription_bp.route("", methods=["GET"])
@jwt_required()
def list_subscriptions():
    subscription_model = Subscription()

    # Optional: if you want, you can add pagination here later!
    subscriptions = subscription_model.get_all()
    return jsonify(subscriptions), 200

# Update subscription status
@admin_subscription_bp.route("/update_status", methods=["POST"])
@jwt_required()
def update_subscription_status():
    data = request.json
    subscription_id = data.get("subscription_id")
    new_status = data.get("status")

    if not subscription_id or not new_status:
        return jsonify({"error": "Missing subscription_id or status"}), 400

    subscription_model = Subscription()
    updated_rows = subscription_model.update_status(subscription_id, new_status)

    if updated_rows == 0:
        return jsonify({"error": "Subscription not found"}), 404

    return jsonify({"message": "Subscription status updated."}), 200

# Cancel subscription
@admin_subscription_bp.route("/cancel", methods=["POST"])
@jwt_required()
def cancel_subscription():
    data = request.json
    subscription_id = data.get("subscription_id")

    if not subscription_id:
        return jsonify({"error": "Missing subscription_id"}), 400

    subscription_model = Subscription()
    updated_rows = subscription_model.update_status(subscription_id, "cancelled")

    if updated_rows == 0:
        return jsonify({"error": "Subscription not found"}), 404

    return jsonify({"message": "Subscription cancelled."}), 200

