from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.conf import settings as django_settings
from .models import Product

@login_required
def product_list_json(request):
    """
    Returns all products as JSON for offline sync / Grid POS.
    Includes image URL and category name.
    """
    products = Product.objects.select_related('category').values(
        "id",
        "name",
        "price",
        "wholesale_price",
        "wholesale_min_quantity",
        "barcode",
        "stock_quantity",
        "image",
        "category__name",
    )

    media_url = request.build_absolute_uri(django_settings.MEDIA_URL)

    result = []
    for p in products:
        img = p.get('image') or ''
        result.append({
            'id':                    p['id'],
            'name':                  p['name'],
            'price':                 str(p['price']),
            'wholesale_price':       str(p['wholesale_price'] or 0),
            'wholesale_min_quantity':p['wholesale_min_quantity'] or 0,
            'barcode':               p['barcode'] or '',
            'stock_quantity':        p['stock_quantity'],
            'image':                 (media_url.rstrip('/') + '/' + img.lstrip('/')) if img else '',
            'category':              p['category__name'] or '',
        })

    return JsonResponse(result, safe=False)