from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from helpdesk.services.ticket_service import ticket_service
from helpdesk.serializers.ticket_list_serializers import TicketListSerializer
from rest_framework.permissions import IsAuthenticated

from drf_spectacular.utils import extend_schema, extend_schema_view

@extend_schema_view(
    list=extend_schema(tags=['2. Application Service']),
    retrieve=extend_schema(tags=['2. Application Service']),
    resolve_ticket=extend_schema(tags=['2. Application Service']),
    assign_ticket=extend_schema(tags=['2. Application Service']),
)
class TicketViewSet(viewsets.ReadOnlyModelViewSet):
    """View สำหรับดึงรายการ Ticket ทั้งหมด (Unified Inbox List)"""
    serializer_class = TicketListSerializer
    permission_classes = [IsAuthenticated]

    # 1. Viewset เรียก Service Layer
    def get_queryset(self):
        return ticket_service.get_inbox_summary()

    # Custom Actions สำหรับการจัดการ Ticket
    @action(detail=True, methods=['post'], url_path='resolve', url_name='resolve')
    @extend_schema(
        summary='ปิด (Resolve) Ticket ด้วย ID',
        description='เปลี่ยนสถานะ Ticket ที่กำหนดให้เป็น "Resolved" หรือ "Closed".',
    )
    def resolve_ticket(self, request, pk=None):
        try:
            updated_ticket = ticket_service.update_ticket_status(
                ticket_id=pk,
                new_status='RESOLVED',
            )
            return Response(self.get_serializer(updated_ticket).data)
        except Exception as e:
            return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'], url_path='assign', url_name='assign')
    @extend_schema(
        summary='มอบหมาย (Assign) Ticket ให้ Agent',
        description='มอบหมาย Ticket นี้ให้กับผู้ใช้/Agent ที่ระบุใน body (เช่น {"assignee_id": 123}).',
        request={
            'application/json': {'type': 'object', 'properties': {'assignee_id': {'type': 'integer'}}}
        }
    )
    def assign_ticket(self, request, pk=None):
        assignee_id = request.data.get('assignee_id')
        if not assignee_id:
            return Response({"assignee_id": "Field is required"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            updated_ticket = ticket_service.assign_ticket_to_user(
                ticket_id=pk,
                assignee_id=assignee_id
            )
            return Response(self.get_serializer(updated_ticket).data)
        except ValueError as e:
            return Response({"detail": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)