from flask import Blueprint, jsonify, request, session
from services.product_service import (
    search_products,
    list_products,
    create_product,
    update_product,
    delete_product,
)

product_bp = Blueprint("product", __name__)

@product_bp.route("/api/urunler/ara")
def urun_ara():
    if not session.get("giris"):
        return jsonify([])

    q = request.args.get("q", "").strip()
    stokta_olan = request.args.get("stokta_olan", "").strip() == "1"

    rows = search_products(q=q, stokta_olan=stokta_olan)
    return jsonify(rows)

@product_bp.route("/api/urunler")
def urun_listele():
    if not session.get("giris"):
        return jsonify([])

    rows = list_products()
    return jsonify(rows)

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

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

@product_bp.route("/api/urunler/<int:urun_id>", methods=["PUT"])
def urun_guncelle(urun_id):
    if not session.get("giris"):
        return jsonify({"ok": False, "hata": "Yetkisiz"}), 401

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

@product_bp.route("/api/urunler/<int:urun_id>", methods=["DELETE"])
def urun_sil(urun_id):
    if not session.get("giris"):
        return jsonify({"ok": False, "hata": "Yetkisiz"}), 401

    result = delete_product(urun_id)
    status = 200 if result.get("ok") else 400
    return jsonify(result), status