from rest_framework import viewsets
from rest_framework.response import Response
from drf_spectacular.utils import extend_schema, OpenApiParameter

from .models import Activity
from .serializers import ActivitySerializer


class ActivityViewSet(viewsets.ModelViewSet):
    """ViewSet for Activity management."""
    rbac_domain = "phonebook"
    queryset = Activity.objects.select_related("user", "contact", "company", "project")
    serializer_class = ActivitySerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    @extend_schema(
        parameters=[
            OpenApiParameter(name="activity_type", type=str, description="Filter by activity type"),
            OpenApiParameter(name="contact", type=str, description="Filter by contact ID"),
            OpenApiParameter(name="company", type=str, description="Filter by company ID"),
            OpenApiParameter(name="project", type=str, description="Filter by project ID"),
            OpenApiParameter(name="is_completed", type=bool, description="Filter by completion status"),
        ]
    )
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        activity_type = request.query_params.get("activity_type")
        if activity_type:
            queryset = queryset.filter(activity_type=activity_type)
        contact = request.query_params.get("contact")
        if contact:
            queryset = queryset.filter(contact_id=contact)
        company = request.query_params.get("company")
        if company:
            queryset = queryset.filter(company_id=company)
        project = request.query_params.get("project")
        if project:
            queryset = queryset.filter(project_id=project)
        is_completed = request.query_params.get("is_completed")
        if is_completed is not None:
            queryset = queryset.filter(is_completed=is_completed.lower() == "true")
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
