# [CRUCIBLE-SEED]
# category: sql_injection
# severity: critical
# language: python
# expected: SQL injection via Django extra()/RawSQL() with user input

from django.db.models import RawSQL
from django.http import JsonResponse
from myapp.models import Product, Order


def product_search(request):
    search = request.GET.get("q", "")
    price_filter = request.GET.get("max_price", "999999")

    # extra() injects raw SQL directly — vulnerable to injection
    products = Product.objects.extra(
        where=["name ILIKE '%%%s%%'" % search, "price <= %s" % price_filter]
    ).values("id", "name", "price")

    return JsonResponse({"products": list(products)})


def revenue_by_region(request):
    group_field = request.GET.get("group_by", "region")
    from django.db import connection
    with connection.cursor() as cur:
        # group_field from user — ORDER BY injection
        cur.execute(
            "SELECT %s, SUM(total) FROM orders GROUP BY %s" % (group_field, group_field)
        )
        rows = cur.fetchall()
    return JsonResponse({"data": rows})
