from rest_framework import viewsets, mixins
from rest_framework.decorators import action
from rest_framework.response import Response
from drf_spectacular.utils import extend_schema, extend_schema_view
from account.permissions import AdminWriteOnlyOrReadOnly
from .models import SiteConfiguration, VATRate
from .serializers import (
	SiteConfigurationSerializer,
	VATRateSerializer,
)


class _SingletonQuerysetMixin:
	def get_queryset(self):
		return SiteConfiguration.objects.filter(pk=1)

	def get_object(self):
		return SiteConfiguration.get_solo()


@extend_schema_view(
	list=extend_schema(tags=["configuration"], summary="List site configuration"),
	retrieve=extend_schema(tags=["configuration"], summary="Retrieve site configuration"),
	create=extend_schema(tags=["configuration"], summary="Create site configuration (admin only)"),
	partial_update=extend_schema(tags=["configuration"], summary="Update site configuration (admin only)"),
	update=extend_schema(tags=["configuration"], summary="Replace site configuration (admin only)"),
	destroy=extend_schema(tags=["configuration"], summary="Delete site configuration (admin only)"),
)
class SiteConfigurationViewSet(_SingletonQuerysetMixin, viewsets.ModelViewSet):
	permission_classes = [AdminWriteOnlyOrReadOnly]
	serializer_class = SiteConfigurationSerializer


@extend_schema_view(
	list=extend_schema(tags=["configuration"], summary="List VAT rates"),
	retrieve=extend_schema(tags=["configuration"], summary="Retrieve VAT rate"),
	create=extend_schema(tags=["configuration"], summary="Create VAT rate (admin only)"),
	partial_update=extend_schema(tags=["configuration"], summary="Update VAT rate (admin only)"),
	update=extend_schema(tags=["configuration"], summary="Replace VAT rate (admin only)"),
	destroy=extend_schema(tags=["configuration"], summary="Delete VAT rate (admin only)"),
)
class VATRateViewSet(viewsets.ModelViewSet):
	"""VAT rate management - read for all, write for admins only"""
	permission_classes = [AdminWriteOnlyOrReadOnly]
	serializer_class = VATRateSerializer
	queryset = VATRate.objects.filter(is_active=True)
	
	def get_queryset(self):
		"""Admins see all rates, others see only active ones"""
		if self.request.user.is_authenticated and getattr(self.request.user, 'role', None) == 'admin':
			return VATRate.objects.all()
		return VATRate.objects.filter(is_active=True)
	
	@extend_schema(
		tags=["configuration"],
		summary="Make VAT rate the default (admin only)",
		description="Set this VAT rate as the default for new products"
	)
	@action(detail=True, methods=['post'])
	def make_default(self, request, pk=None):
		"""Make this VAT rate the default"""
		vat_rate = self.get_object()
		
		# Clear existing defaults
		VATRate.objects.filter(is_default=True).update(is_default=False)
		
		# Set new default
		vat_rate.is_default = True
		vat_rate.save()
		
		return Response({
			'message': f'"{vat_rate.name}" is now the default VAT rate',
			'default_rate_id': vat_rate.id
		})