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
from core.models import SystemSettings

@login_required
def product_list_json(request):
    """
    Returns all products as JSON for offline sync / Grid POS.
    Includes image URL and category name.
    - Includes image URL, category name, and global unlimited stock setting.
    """
    settings = SystemSettings.objects.first()
    enable_unlimited_stock = settings.enable_unlimited_stock if settings else False

    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 '',
            'enable_unlimited_stock': enable_unlimited_stock,
        })

    return JsonResponse(result, safe=False)