from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework import status
from django.db import transaction
from .models import Task
from .serializers import TaskSerializer
from ErrorLogs.utils import log_error

@api_view(['GET', 'POST'])
@permission_classes([AllowAny])
def task_list(request):
    if request.method == 'GET':
        try:
            tasks = Task.objects.all()
            # Filter by project if provided
            project_id = request.query_params.get('project', None)
            if project_id:
                tasks = tasks.filter(project_id=project_id)
            serializer = TaskSerializer(tasks, many=True)
            return Response(serializer.data)
        except Exception as e:
            log_error('task_list.GET', e)
            return Response(
                {"error": "An error occurred while fetching tasks"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    elif request.method == 'POST':
        try:
            with transaction.atomic():
                serializer = TaskSerializer(data=request.data)
                if serializer.is_valid():
                    serializer.save()
                    return Response(serializer.data, status=status.HTTP_201_CREATED)
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            log_error('task_list.POST', e)
            return Response(
                {"error": "An error occurred while creating task"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([AllowAny])
def task_detail(request, pk):
    try:
        task = Task.objects.get(pk=pk)
    except Task.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        log_error('task_detail.get_task', e)
        return Response(
            {"error": "An error occurred while fetching task"},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )

    if request.method == 'GET':
        try:
            serializer = TaskSerializer(task)
            return Response(serializer.data)
        except Exception as e:
            log_error('task_detail.GET', e)
            return Response(
                {"error": "An error occurred while fetching task details"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    elif request.method == 'PUT':
        try:
            with transaction.atomic():
                serializer = TaskSerializer(task, data=request.data)
                if serializer.is_valid():
                    serializer.save()
                    return Response(serializer.data)
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            log_error('task_detail.PUT', e)
            return Response(
                {"error": "An error occurred while updating task"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    elif request.method == 'DELETE':
        try:
            with transaction.atomic():
                task.delete()
                return Response(status=status.HTTP_204_NO_CONTENT)
        except Exception as e:
            log_error('task_detail.DELETE', e)
            return Response(
                {"error": "An error occurred while deleting task"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

