from flask import Blueprint, jsonify, request, session
from services.sales_service import create_sale, create_gecmis_sale, list_sales

sales_bp = Blueprint("sales", __name__)

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

    data = request.get_json(silent=True) or {}
    result = create_sale(data)
    status = 200 if result.get("ok") else 400
    return jsonify(result), status

@sales_bp.route("/api/satislar/gecmis", methods=["POST"])
def gecmis_satis_ekle():
    if not session.get("giris"):
        return jsonify({"ok": False, "hata": "Yetkisiz"}), 401

    data = request.get_json(silent=True) or {}
    result = create_gecmis_sale(data)
    status = 200 if result.get("ok") else 400
    return jsonify(result), status

@sales_bp.route("/api/satislar")
def satis_listele():
    if not session.get("giris"):
        return jsonify([])

    q      = request.args.get("q", "").strip() or None
    tarih  = request.args.get("tarih", "").strip() or None
    durum  = request.args.get("durum", "").strip() or None

    rows = list_sales(q=q, tarih=tarih, durum=durum)
    return jsonify(rows)