from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models.order_out import OrdersOut  # Your plain SQL model
from datetime import datetime
from models.user import Users

report_order_out_bp = Blueprint("report_order_out", __name__, url_prefix="/report_order_out")

@report_order_out_bp.route("/profit", methods=["GET"])
@jwt_required()
def get_profit_report():
    try:
        user_id = get_jwt_identity()
        users = Users()
        user = users.get_user_by_id(user_id)
        if user['user_role'] == 'company_user':
            user_id = user['company_id']
        # Get filters from query params
        date_from = request.args.get("date_from")
        date_to = request.args.get("date_to")
        client_id = request.args.get("client_id")
        transporter_id = request.args.get("transporter_id")

        # Use the plain SQL method that returns filtered orders list
        filters = {
            "user_id": user_id,
            "date_from": date_from,
            "date_to": date_to,
            "client_id": client_id,
            "transporter_id": transporter_id
        }

        orders = OrdersOut.get_filtered_orders(filters)  # Implement this method in your model

        total_received = sum(float(o.get("price_received", 0) or 0) for o in orders)
        total_paid = sum(float(o.get("price_paid", 0) or 0) for o in orders)
        profit = total_received - total_paid

        return jsonify({
            "total_received": total_received,
            "total_paid": total_paid,
            "profit": profit,
            "orders_count": len(orders)
        })

    except Exception as e:
        return jsonify({"error": str(e)}), 500