from flask import Blueprint, jsonify, request, session
from services.payment_service import get_customer_sales, add_payment

payment_bp = Blueprint("payment", __name__)

@payment_bp.route("/api/odeme/musteri/<int:musteri_id>")
def musteri_satislari(musteri_id):
    if not session.get("giris"):
        return jsonify([]), 401
    satislar = get_customer_sales(musteri_id)
    return jsonify(satislar)

@payment_bp.route("/api/odeme/ekle", methods=["POST"])
def odeme_ekle():
    if not session.get("giris"):
        return jsonify({"ok": False, "hata": "Yetkisiz"}), 401

    data = request.get_json(silent=True) or {}
    satis_id = data.get("satis_id")
    miktar = data.get("miktar")
    notlar = data.get("notlar", "")

    if not satis_id:
        return jsonify({"ok": False, "hata": "Satış ID gerekli"}), 400

    try:
        miktar = float(miktar)
    except (TypeError, ValueError):
        return jsonify({"ok": False, "hata": "Geçersiz miktar"}), 400

    result = add_payment(satis_id, miktar, notlar)
    status = 200 if result.get("ok") else 400
    return jsonify(result), status
