# structures/views_city_tax.py

from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from django.shortcuts import get_object_or_404
from django.db import transaction

from drf_spectacular.utils import (
    extend_schema,
    OpenApiExample,
    OpenApiResponse,
)

from structures.models import Structure
from .models import (
    StructureCityTaxSettings,
    CityTaxMonthlyRate,
)
from .serializers_city_tax import (
    StructureCityTaxSettingsSerializer,
    CityTaxMonthlyRateNestedSerializer,
)

# ============================================================
# CITY TAX SETTINGS API
# GET / POST / PUT
# /api/structures/{structure_id}/city-tax/settings/
# ============================================================

@extend_schema(
    tags=["City Tax"],
    summary="Get, create or update city tax settings for a structure",
    request=StructureCityTaxSettingsSerializer,   # ← THIS FIXES PAYLOAD UI
    responses={
        200: StructureCityTaxSettingsSerializer,
        201: StructureCityTaxSettingsSerializer,
        400: OpenApiResponse(description="Validation error"),
        404: OpenApiResponse(description="Structure not found"),
        409: OpenApiResponse(description="City tax settings already exist"),
    },
    examples=[
        OpenApiExample(
            name="Create / Update Payload",
            value={
                "default_rate": 3,
                "max_taxable_nights": 8,
                "minor_age_limit": 14,
                "exemption_reasons": ["Medical", "Student", "Refugee", "Resident"],
                "platform_exemptions": ["airbnb"],
                "city_taxes": [
                    {"year": 2025, "month": 7, "rate": 3},
                    {"year": 2026, "month": 7, "rate": 3}
                ],
                "is_active": True
            },
            request_only=True
        ),
        OpenApiExample(
            name="Success Response",
            value={
                "default_rate": 3,
                "max_taxable_nights": 8,
                "minor_age_limit": 14,
                "exemption_reasons": [
                    "Medical",
                    "Student",
                    "Refugee",
                    "Resident",
                    "Minor"
                ],
                "platform_exemptions": ["airbnb"],
                "city_taxes": [
                    {"year": 2025, "month": 7, "rate": 3}
                ],
                "is_active": True
            },
            response_only=True
        )
    ],
)
class StructureCityTaxSettingsAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, structure_id):
        structure = get_object_or_404(Structure, id=structure_id)

        try:
            settings = structure.city_tax_settings
        except StructureCityTaxSettings.DoesNotExist:
            # No settings yet is NOT an error
            return Response({}, status=status.HTTP_200_OK)

        serializer = StructureCityTaxSettingsSerializer(settings)
        # Pull monthly rates via related_name
        city_taxes = CityTaxMonthlyRate.objects.filter(
            structure_id=self.kwargs["structure_id"]
        ).order_by("year", "month")

        city_taxes_data = CityTaxMonthlyRateNestedSerializer(
            city_taxes,
            many=True
        ).data

        data = serializer.data
        data["city_taxes"] = city_taxes_data

        return Response(data, status=status.HTTP_200_OK)

    def post(self, request, structure_id):
        structure = get_object_or_404(Structure, id=structure_id)

        if hasattr(structure, "city_tax_settings"):
            return Response(
                {"detail": "City tax settings already exist for this structure."},
                status=status.HTTP_409_CONFLICT
            )

        serializer = StructureCityTaxSettingsSerializer(
            data=request.data,
            context={"structure": structure}
        )
        serializer.is_valid(raise_exception=True)

        with transaction.atomic():
            settings = serializer.save()

        return Response(
            StructureCityTaxSettingsSerializer(settings).data,
            status=status.HTTP_201_CREATED
        )

    def put(self, request, structure_id):
        structure = get_object_or_404(Structure, id=structure_id)

        settings = get_object_or_404(
            StructureCityTaxSettings,
            structure=structure
        )

        serializer = StructureCityTaxSettingsSerializer(
            settings,
            data=request.data,
            context={"structure": structure}
        )
        serializer.is_valid(raise_exception=True)

        with transaction.atomic():
            settings = serializer.save()

        return Response(
            StructureCityTaxSettingsSerializer(settings).data,
            status=status.HTTP_200_OK
        )


# ============================================================
# CITY TAX RATES API (READ ONLY)
# GET
# /api/structures/{structure_id}/city-tax/rates/
# ============================================================

@extend_schema(
    tags=["City Tax"],
    summary="Get monthly city tax rates for a structure",
    responses={
        200: CityTaxMonthlyRateNestedSerializer(many=True),
        404: OpenApiResponse(description="Structure not found"),
    },
    examples=[
        # ---------- SUCCESS ----------
        OpenApiExample(
            name="GET – Monthly Rates",
            value=[
                {"year": 2025, "month": 7, "rate": 3.00},
                {"year": 2025, "month": 8, "rate": 3.00},
                {"year": 2025, "month": 9, "rate": 3.50}
            ],
            response_only=True
        ),
        # ---------- EMPTY ----------
        OpenApiExample(
            name="GET – No Rates Configured",
            value=[],
            response_only=True
        ),
    ],
)
class CityTaxRatesAPIView(ListAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = CityTaxMonthlyRateNestedSerializer

    def get_queryset(self):
        # 404 if structure does not exist
        get_object_or_404(Structure, id=self.kwargs["structure_id"])

        return CityTaxMonthlyRate.objects.filter(
            structure_id=self.kwargs["structure_id"]
        ).order_by("year", "month")
