from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from .models import ConfigurationTranslation
from .serializers import ConfigurationTranslationSerializer
from ErrorLogs.utils import log_error


@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def translation_list(request):
    """
    GET: List all translations
    POST: Create a new translation
    """
    if request.method == 'GET':
        try:
            translations = ConfigurationTranslation.objects.all()
            
            # Filter by translation_type if provided
            translation_type = request.query_params.get('translation_type')
            if translation_type:
                translations = translations.filter(translation_type=translation_type)
            
            # Filter by language if provided
            language = request.query_params.get('language')
            if language:
                translations = translations.filter(language=language)
            
            # Filter by reference_id if provided
            reference_id = request.query_params.get('reference_id')
            if reference_id:
                translations = translations.filter(reference_id=reference_id)
            
            serializer = ConfigurationTranslationSerializer(translations, many=True)
            return Response(serializer.data)
        except Exception as e:
            log_error('translation_list.GET', e)
            return Response(
                {"error": "An error occurred while fetching translations"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    elif request.method == 'POST':
        try:
            serializer = ConfigurationTranslationSerializer(data=request.data)
            if serializer.is_valid():
                translation = serializer.save()
                response_serializer = ConfigurationTranslationSerializer(translation)
                return Response(response_serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            log_error('translation_list.POST', e)
            return Response(
                {"error": "An error occurred while creating translation"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([IsAuthenticated])
def translation_detail(request, pk):
    """
    GET: Get a specific translation
    PUT: Update a translation
    DELETE: Delete a translation
    """
    try:
        translation = ConfigurationTranslation.objects.get(pk=pk)
    except ConfigurationTranslation.DoesNotExist:
        return Response(
            {"error": "Translation not found"},
            status=status.HTTP_404_NOT_FOUND
        )
    except Exception as e:
        log_error('translation_detail.get_translation', e)
        return Response(
            {"error": "An error occurred while fetching translation"},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )
    
    if request.method == 'GET':
        try:
            serializer = ConfigurationTranslationSerializer(translation)
            return Response(serializer.data)
        except Exception as e:
            log_error('translation_detail.GET', e)
            return Response(
                {"error": "An error occurred while fetching translation details"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    elif request.method == 'PUT':
        try:
            serializer = ConfigurationTranslationSerializer(translation, data=request.data)
            if serializer.is_valid():
                updated_translation = serializer.save()
                response_serializer = ConfigurationTranslationSerializer(updated_translation)
                return Response(response_serializer.data)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            log_error('translation_detail.PUT', e)
            return Response(
                {"error": "An error occurred while updating translation"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    elif request.method == 'DELETE':
        try:
            translation.delete()
            return Response(
                {"message": "Translation deleted successfully"},
                status=status.HTTP_204_NO_CONTENT
            )
        except Exception as e:
            log_error('translation_detail.DELETE', e)
            return Response(
                {"error": "An error occurred while deleting translation"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

