from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models.payments.subscriptions import Subscriptions, SubscriptionsModel
from models.audit import Audit, AuditModel

subscriptions_bp = Blueprint("subscriptions", __name__)
audit = Audit()

@subscriptions_bp.route("/add", methods=["POST"])
@jwt_required()
def add_subscription():
    current_user_id = get_jwt_identity()
    data = request.get_json()
    
    name = data.get("name")
    pay_and_subs_id = data.get("pay_and_subs_id")
    mounts = data.get("mounts")
    
    if not name or not pay_and_subs_id:
        return jsonify({"error": "Missing required fields (name, pay_and_subs_id)"}), 400

    subs_repo = Subscriptions()
    new_sub = SubscriptionsModel(
        user_id=current_user_id,
        name=name,
        pay_and_subs_id=pay_and_subs_id,
        mounts=mounts
    )

    sub_id = subs_repo.add_subscription(new_sub)
    if sub_id:
        audit.new_entry(AuditModel(user_id=current_user_id, action=f"Added subscription: {name}", status="201 - Created"))
        return jsonify({"message": "Subscription added successfully", "id": sub_id}), 201
    
    return jsonify({"error": "Failed to add subscription"}), 500

@subscriptions_bp.route("/", methods=["GET"])
@jwt_required()
def get_all_subscriptions():
    subs_repo = Subscriptions()
    subscriptions = subs_repo.get_all_subscriptions()
    return jsonify([vars(s) for s in subscriptions]), 200

@subscriptions_bp.route("/<int:subscription_id>", methods=["GET"])
@jwt_required()
def get_subscription(subscription_id):
    subs_repo = Subscriptions()
    subscription = subs_repo.get_subscription(subscription_id)
    if not subscription:
        return jsonify({"error": "Subscription not found"}), 404
    return jsonify(vars(subscription)), 200

@subscriptions_bp.route("/update/<int:subscription_id>", methods=["PUT"])
@jwt_required()
def update_subscription(subscription_id):
    current_user_id = get_jwt_identity()
    data = request.get_json()
    subs_repo = Subscriptions()
    
    success = subs_repo.update_subscription(
        subscription_id,
        name=data.get("name"),
        pay_and_subs_id=data.get("pay_and_subs_id"),
        mounts=data.get("mounts")
    )

    if success:
        audit.new_entry(AuditModel(user_id=current_user_id, action=f"Updated subscription ID: {subscription_id}", status="200 - OK"))
        return jsonify({"message": "Subscription updated successfully"}), 200
    
    return jsonify({"error": "Subscription not found or no valid fields to update"}), 404