import os
import shutil
from flask import Blueprint, request, jsonify, send_from_directory
from flask_jwt_extended import jwt_required, get_jwt_identity
from models.payments.payments import Payments, PaymentsModel
from models.audit import Audit, AuditModel

payments_bp = Blueprint("payments", __name__)
audit = Audit()

@payments_bp.route("/add", methods=["POST"])
@jwt_required()
def add_payment():
    current_user_id = get_jwt_identity()
    data = request.get_json()
    
    name = data.get("name")
    amount = data.get("amount")
    payment_type = data.get("type")
    
    if not name or amount is None or not payment_type:
        return jsonify({"error": "Missing required fields (name, amount, type)"}), 400

    payment_repo = Payments()
    new_payment = PaymentsModel(
        user_id=current_user_id,
        name=name,
        amount=float(amount),
        type=payment_type
    )

    payment_id = payment_repo.add_payment(new_payment)
    if payment_id:
        audit.new_entry(AuditModel(user_id=current_user_id, action=f"Added payment: {name}", status="201 - Created"))
        return jsonify({"message": "Payment added successfully", "id": payment_id}), 201
    
    return jsonify({"error": "Failed to add payment"}), 500

@payments_bp.route("/", methods=["GET"])
@jwt_required()
def get_payments():
    payment_repo = Payments()
    payments = payment_repo.get_all_payments()
    return jsonify([vars(p) for p in payments]), 200

@payments_bp.route("/<int:payment_id>", methods=["GET"])
@jwt_required()
def get_payment(payment_id):
    payment_repo = Payments()
    payment = payment_repo.get_payment(payment_id)
    if not payment:
        return jsonify({"error": "Payment not found"}), 404
    return jsonify(vars(payment)), 200

@payments_bp.route("/update/<int:payment_id>", methods=["PUT"])
@jwt_required()
def update_payment(payment_id):
    current_user_id = get_jwt_identity()
    data = request.get_json()
    payment_repo = Payments()
    
    success = payment_repo.update_payment(
        payment_id,
        name=data.get("name"),
        amount=float(data.get("amount")) if data.get("amount") is not None else None,
        type=data.get("type")
    )

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

@payments_bp.route("/delete/<int:payment_id>", methods=["DELETE"])
@jwt_required()
def delete_payment(payment_id):
    current_user_id = get_jwt_identity()
    payment_repo = Payments()
    
    if payment_repo.delete_payment(payment_id):
        audit.new_entry(AuditModel(user_id=current_user_id, action=f"Deleted payment ID: {payment_id}", status="200 - OK"))
        return jsonify({"message": "Payment deleted successfully"}), 200
    
    return jsonify({"error": "Payment not found"}), 404