from flask import Blueprint, jsonify, request, session
from services.customer_service import search_customers, create_customer, get_customer_detail

customer_bp = Blueprint("customer", __name__)

@customer_bp.route("/api/musteriler/ara")
def musteri_ara():
    if not session.get("giris"):
        return jsonify([])

    q = request.args.get("q", "").strip()
    rows = search_customers(q=q)
    return jsonify(rows)

@customer_bp.route("/api/musteriler/<int:musteri_id>")
def musteri_detay(musteri_id):
    if not session.get("giris"):
        return jsonify({"ok": False, "hata": "Yetkisiz"}), 401

    detail = get_customer_detail(musteri_id)
    if not detail:
        return jsonify({"ok": False, "hata": "Müşteri bulunamadı"}), 404

    return jsonify({"ok": True, **detail})

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

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