from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication, SessionAuthentication
from rest_framework.response import Response
from rest_framework import status
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from core.serializers.MeetingSerializer import MeetingSerializer
 

# @swagger_auto_schema(
#     method='post',
#     request_body=openapi.Schema(
#         type=openapi.TYPE_OBJECT,
#         required=['name', 'description', 'date_time'],
#         properties={
#             'name': openapi.Schema(type=openapi.TYPE_STRING, default='Sprint Planning'),
#             'description': openapi.Schema(type=openapi.TYPE_STRING, default='Discuss the next sprint'),
#             'date_time': openapi.Schema(type=openapi.TYPE_STRING, format='date-time', default='2025-06-01T14:00:00Z'),
#             'space': openapi.Schema(type=openapi.TYPE_INTEGER, default=1),
#             'asset_bundle': openapi.Schema(type=openapi.TYPE_INTEGER, default=1),
#             'use_space': openapi.Schema(type=openapi.TYPE_BOOLEAN, default=False),
#         }
#     )
# )
# @api_view(['POST'])
# @authentication_classes([SessionAuthentication, TokenAuthentication])
# @permission_classes([IsAuthenticated])
# def addMeeting(request):
#     data = request.data.copy()
#     data['creator_user'] = request.user.id

#     serializer = MeetingSerializer(data=data)
#     if serializer.is_valid():
#         meeting = serializer.save()
#         return Response({
#             "message": "Meeting created successfully.",
#             "meeting": serializer.data
#         }, status=status.HTTP_201_CREATED)

#     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)








from core.models.Invitation import  Invitation  # Ensure Invitation is imported
from django.contrib.auth.models import User
from django.db import transaction

@swagger_auto_schema(
    method='post',
    request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        required=['name', 'description', 'date_time', 'user_ids'],
        properties={
            'name': openapi.Schema(type=openapi.TYPE_STRING, default='Sprint Planning'),
            'description': openapi.Schema(type=openapi.TYPE_STRING, default='Discuss the next sprint'),
            'date_time': openapi.Schema(type=openapi.TYPE_STRING, format='date-time', default='2025-06-01T14:00:00Z'),
            'space': openapi.Schema(type=openapi.TYPE_INTEGER, default=1),
            'asset_bundle': openapi.Schema(type=openapi.TYPE_INTEGER, default=1),
            'use_space': openapi.Schema(type=openapi.TYPE_BOOLEAN, default=False),
            'user_ids': openapi.Schema(
                type=openapi.TYPE_ARRAY,
                items=openapi.Items(type=openapi.TYPE_INTEGER),
                description='List of user IDs to invite'
            ),
        }
    )
)
@api_view(['POST'])
@authentication_classes([SessionAuthentication, TokenAuthentication])
@permission_classes([IsAuthenticated])
def addMeeting(request):
    data = request.data.copy()
    user_ids = data.pop('user_ids', [])
    data['creator_user'] = request.user.id

    serializer = MeetingSerializer(data=data)

    if serializer.is_valid():
        try:
            with transaction.atomic():
                meeting = serializer.save()

                for user_id in user_ids:
                    user = User.objects.get(id=user_id)  # will raise exception if not found
                    Invitation.objects.create(
                        user=user,
                        meeting=meeting,
                        is_admin=False,
                        is_sms_sent=False
                    )

                return Response({
                    "message": "Meeting created successfully with invitations.",
                    "meeting": serializer.data
                }, status=status.HTTP_201_CREATED)

        except User.DoesNotExist:
            return Response(
                {"error": f"User with id {user_id} does not exist."},
                status=status.HTTP_400_BAD_REQUEST
            )
        except Exception as e:
            return Response(
                {"error": str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)