import logging

from requests.exceptions import RequestException
from rest_framework import generics, serializers, status
from rest_framework.response import Response

from common.views import APIKeyAuthentication, DashboardTokenAuthentication

from .pms.analyze_product import analyzeProduct
from .pms.import_product import AliExpressUpstreamError, importProduct
from .pms.save_product import saveProduct
from .searlizers import ImportAndAnalyzeProductRequestSerializer

logger = logging.getLogger(__name__)


class ImportAndAnalyzeProductDashboardView(generics.GenericAPIView):
    """Import an AliExpress product, analyze it, and return the analysis."""

    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    serializer_class = ImportAndAnalyzeProductRequestSerializer
    queryset = []

    def post(self, request, *args, **kwargs):
        required_fields = (
            "shipToCountry",
            "productId",
            "targetCurrency",
            "targetLanguage",
            "currencyId",
            "languageId",
            "collectionId",
        )
        missing_fields = [
            field
            for field in required_fields
            if request.data.get(field) is None or request.data.get(field) == ""
        ]
        if missing_fields:
            return Response(
                {
                    "error": "Missing required fields.",
                    "missingFields": missing_fields,
                },
                status=400,
            )

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        try:
            import_data = serializer.validated_data.copy()
            save_ids = {
                key: import_data.pop(key)
                for key in ("currencyId", "languageId", "collectionId")
            }
            imported_product = importProduct(**import_data)
            analysis = analyzeProduct(imported_product)
        except (AliExpressUpstreamError, RequestException) as error:
            return Response(
                {
                    "error": "AliExpress request failed.",
                    "detail": str(error),
                },
                status=status.HTTP_502_BAD_GATEWAY,
            )

        analysis["isProductSave"] = False
        if analysis.get("decision") in ("SELL", "CONSIDER"):
            try:
                saveProduct(imported_product, **save_ids)
                analysis["isProductSave"] = True
            except Exception:
                logger.exception(
                    "Failed to save analyzed AliExpress product %s",
                    serializer.validated_data["productId"],
                )

        return Response(analysis)
