from django.apps import apps

from drf_spectacular.utils import OpenApiExample, extend_schema
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from config.openapi import build_envelope_serializer, build_response

from .serializers import (
    EconomicOverviewRequestSerializer,
    EconomicOverviewResponseSerializer,
)


EconomicOverviewEnvelopeSerializer = build_envelope_serializer(
    "EconomicOverviewEnvelopeSerializer",
    EconomicOverviewResponseSerializer,
)
EconomyErrorSerializer = build_envelope_serializer(
    "EconomyErrorSerializer",
    data_required=False,
    allow_null=True,
)


class EconomicOverviewView(APIView):
    @extend_schema(
        tags=["Economy"],
        summary="دریافت نمای اقتصادی مزرعه",
        description="با دریافت farm_uuid، نمای اقتصادی مزرعه را از منبع واقعی برمی گرداند.",
        request=EconomicOverviewRequestSerializer,
        responses={
            200: build_response(
                EconomicOverviewEnvelopeSerializer,
                "نمای اقتصادی مزرعه با موفقیت بازگردانده شد.",
            ),
            400: build_response(
                EconomyErrorSerializer,
                "داده ورودی نامعتبر است.",
            ),
            503: build_response(
                EconomyErrorSerializer,
                "منبع داده نمای اقتصادی در دسترس نیست.",
            ),
        },
        examples=[
            OpenApiExample(
                "نمونه درخواست economy",
                value={"farm_uuid": "11111111-1111-1111-1111-111111111111"},
                request_only=True,
            )
        ],
    )
    def post(self, request):
        serializer = EconomicOverviewRequestSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {"code": 400, "msg": "داده نامعتبر.", "data": serializer.errors},
                status=status.HTTP_400_BAD_REQUEST,
            )

        service = apps.get_app_config("economy").get_economic_overview_service()
        try:
            data = service.get_economic_overview(
                farm_uuid=str(serializer.validated_data["farm_uuid"])
            )
        except NotImplementedError as exc:
            return Response(
                {"code": 503, "msg": str(exc), "data": None},
                status=status.HTTP_503_SERVICE_UNAVAILABLE,
            )
        return Response(
            {"code": 200, "msg": "success", "data": data},
            status=status.HTTP_200_OK,
        )
