# vouchers/api.py
import requests
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .services import pull_voucher
from .services import BASE_URL

# from .utils import encrypt_payload, decrypt_payload
# from .services import get_token


class PullVoucherAPIView(APIView):
    def post(self, request):
        data = request.data
        required_fields = ['brand_product_code', 'denomination', 'quantity', 'order_id']
        missing = [f for f in required_fields if f not in data]

        if missing:
            return Response({"success": False, "error": f"Missing fields: {', '.join(missing)}"}, status=400)

        result = pull_voucher(
            brand_product_code=data['brand_product_code'],
            denomination=data['denomination'],
            quantity=data['quantity'],
            order_id=data['order_id']
        )

        return Response(result, status=200 if result.get('success') else 400)

# ✅ 1. /api/brands/ – List Available Brands
# vouchers/api.py (add below PullVoucherAPIView)
from rest_framework.generics import ListAPIView
from .models import Brand
from .serializers import BrandSerializer

class BrandListAPIView(ListAPIView):
    queryset = Brand.objects.all()
    serializer_class = BrandSerializer

# ✅ 2. /api/brand-stock/ – Check Brand Stock
from rest_framework.views import APIView

class BrandStockAPIView(APIView):
    def post(self, request):
        from .services import get_token
        from .utils import encrypt_payload, decrypt_payload

        brand_code = request.data.get("brand_product_code")
        denomination = request.data.get("denomination")
        if not brand_code or not denomination:
            return Response({"success": False, "error": "Missing brand_product_code or denomination"}, status=400)

        token = get_token()
        if not token:
            return Response({"success": False, "error": "Token fetch failed"}, status=500)

        payload = encrypt_payload({
            "BrandProductCode": brand_code,
            "Denomination": str(denomination)
        })

        headers = {"Content-Type": "application/json", "token": token}
        res = requests.post(f"{BASE_URL}/getstock", headers=headers, json={"payload": payload})

        if res.status_code == 200:
            decrypted = decrypt_payload(res.json().get("data", ""))
            return Response({"success": True, "data": decrypted})
        return Response({"success": False, "error": "API failed", "response": res.text}, status=res.status_code)

# ✅ 3. /api/store-list/ – Get Store List for a Brand
class StoreListAPIView(APIView):
    def post(self, request):
        from .services import get_token
        brand_code = request.data.get("brand_product_code")
        shop = request.data.get("shop", "")

        if not brand_code:
            return Response({"success": False, "error": "Missing brand_product_code"}, status=400)

        token = get_token()
        if not token:
            return Response({"success": False, "error": "Token fetch failed"}, status=500)

        headers = {"Content-Type": "application/json", "token": token}
        payload = {"BrandProductCode": brand_code, "shop": shop}
        res = requests.post(f"{BASE_URL}/getstorelist", headers=headers, json=payload)

        try:
            return Response(res.json())
        except:
            return Response({"success": False, "error": "Invalid response", "raw": res.text})

# ✅ 4. /api/voucher-history/ – View Purchase History
from .models import VoucherPurchaseHistory
from .serializers import VoucherPurchaseSerializer
from rest_framework.generics import ListAPIView

class VoucherHistoryAPIView(ListAPIView):
    queryset = VoucherPurchaseHistory.objects.select_related('brand').all().order_by('-created_at')
    serializer_class = VoucherPurchaseSerializer

# ✅ 5. Update urls.py
# vouchers/urls.py

from .models import Voucher
from .serializers import VoucherSerializer
from rest_framework.generics import ListAPIView

class VoucherListAPIView(ListAPIView):
    queryset = Voucher.objects.select_related('brand').all().order_by('-created_at')
    serializer_class = VoucherSerializer
