"""Product views. Delegate to products.services."""
from django.http import JsonResponse
from django.views import View

from products.services import ProductService


class ProductListView(View):
    """GET /products/ — list products from DB. Query: ?limit=100&offset=0."""

    def get(self, request):
        limit = min(int(request.GET.get("limit", 100)), 500)
        offset = max(0, int(request.GET.get("offset", 0)))
        items = ProductService.list_from_db(limit=limit, offset=offset)
        return JsonResponse({"ok": True, "products": items, "count": len(items)})


class ProductSyncView(View):
    """POST /products/sync/<shopify_product_id>/ — sync a single product."""

    def post(self, request, shopify_product_id: str):
        result = ProductService.sync_product(shopify_product_id)
        status = 200 if result.get("ok") else 400
        return JsonResponse(result, status=status)


class ProductSyncAllView(View):
    """POST /products/sync-all/ — sync all products from Shopify. Query: ?limit=250."""

    def post(self, request):
        limit = min(int(request.GET.get("limit", 250)), 500)
        result = ProductService.sync_all(limit=limit)
        status = 200 if result.get("ok") else 400
        return JsonResponse(result, status=status)


class ProductIdLookupView(View):
    """
    GET /products/digistore/id?id=<shopify_product_id_or_variant_id>

    Public endpoint to resolve a Digistore product id from a Shopify product id
    or variant id.
    """

    def get(self, request):
        product_id = (request.GET.get("id") or "").strip()
        if not product_id:
            return JsonResponse({"error": "missing id"}, status=400)

        digistore_id = ProductService.lookup_digistore_product_id(product_id)
        if not digistore_id:
            return JsonResponse({"error": "not found"}, status=404)

        return JsonResponse({"digistore_id": digistore_id})
