"""
Currency Views — API views.
"""
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from .models import Currency, ExchangeRate
from .serializers import (
    CurrencySerializer,
    CurrencyCreateSerializer,
    ExchangeRateSerializer,
)


class CurrencyViewSet(viewsets.ModelViewSet):
    """CRUD ارزها."""

    serializer_class = CurrencySerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        qs = Currency.objects.all()
        is_active = self.request.query_params.get("is_active")
        if is_active is not None:
            qs = qs.filter(is_active=is_active.lower() == "true")
        return qs.order_by("-is_base", "code")

    def get_serializer_class(self):
        if self.action in ("create", "update", "partial_update"):
            return CurrencyCreateSerializer
        return CurrencySerializer

    @action(detail=False, methods=["get"])
    def base(self, request):
        """دریافت ارز پایه Tenant."""
        currency = Currency.objects.filter(is_base=True).first()
        if not currency:
            return Response(
                {"error": {"code": "NO_BASE_CURRENCY", "message": "ارز پایه تعریف نشده"}},
                status=status.HTTP_404_NOT_FOUND,
            )
        return Response(CurrencySerializer(currency).data)


class ExchangeRateViewSet(viewsets.ModelViewSet):
    """CRUD نرخ تبدیل."""

    serializer_class = ExchangeRateSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        qs = ExchangeRate.objects.select_related(
            "from_currency", "to_currency"
        )
        from_code = self.request.query_params.get("from")
        to_code = self.request.query_params.get("to")
        if from_code:
            qs = qs.filter(from_currency__code=from_code.upper())
        if to_code:
            qs = qs.filter(to_currency__code=to_code.upper())
        return qs.order_by("-effective_date")

    @action(detail=False, methods=["get"])
    def latest(self, request):
        """آخرین نرخ تبدیل بین دو ارز."""
        from_code = request.query_params.get("from", "").upper()
        to_code = request.query_params.get("to", "").upper()
        if not from_code or not to_code:
            return Response(
                {"error": {"code": "MISSING_PARAMS", "message": "پارامتر from و to الزامی است"}},
                status=status.HTTP_400_BAD_REQUEST,
            )
        rate = (
            ExchangeRate.objects.filter(
                from_currency__code=from_code,
                to_currency__code=to_code,
            )
            .order_by("-effective_date")
            .first()
        )
        if not rate:
            return Response(
                {"error": {"code": "NOT_FOUND", "message": "نرخ تبدیل یافت نشد"}},
                status=status.HTTP_404_NOT_FOUND,
            )
        return Response(ExchangeRateSerializer(rate).data)
