from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status

from core.models.Team import Team
from core.models.TeamMember import TeamMember
from core.serializers.TeamSerializer import TeamSerializer


from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema





@swagger_auto_schema(
    method='post',
    request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        required=['name', 'description', 'max_persons', 'subscriptionId'],
        properties={
            'name': openapi.Schema(type=openapi.TYPE_STRING, default='team1'),
            'description': openapi.Schema(type=openapi.TYPE_STRING, default='TEST DES'),
            'max_persons': openapi.Schema(type=openapi.TYPE_STRING, default='9'),
            'subscriptionId': openapi.Schema(type=openapi.TYPE_STRING, default='1'),
        }
    )
)
@api_view(['POST'])
@authentication_classes([SessionAuthentication, TokenAuthentication])
@permission_classes([IsAuthenticated])
def addTeam(request):
    data = request.data.copy()
    data['admin'] = request.user.id
    data['subscription'] = data.get('subscriptionId')  # Map subscriptionId to FK field

    serializer = TeamSerializer(data=data)

    if serializer.is_valid():
        team = serializer.save()
        return Response({
            "message": "Team created successfully.",
            "team": serializer.data
        }, status=status.HTTP_201_CREATED)

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






@api_view(['GET'])
@authentication_classes([SessionAuthentication, TokenAuthentication])
@permission_classes([IsAuthenticated])
def getTeams(request):
    user = request.user
    teams = Team.objects.filter(admin=user)
    serializer = TeamSerializer(teams, many=True)

    return Response({
        "teams": serializer.data
    }, status=status.HTTP_200_OK)









from django.contrib.auth.models import User
from django.db.models import Q

from rest_framework.serializers import ModelSerializer


class SimpleUserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'first_name', 'last_name' ]

@api_view(['GET'])
@authentication_classes([SessionAuthentication, TokenAuthentication])
@permission_classes([IsAuthenticated])
def get_all_team_members(request):
    try:
            # Get all team IDs for current user
            # team_ids = TeamMember.objects.filter(user=request.user).values_list('team_id', flat=True)
            # team_ids = Team.objects.filter(Q(members__user=request.user) | Q(admin=request.user)).values_list('id', flat=True).distinct()
            
            # team_ids = Team.objects.filter(admin_id=7)
            team_ids = Team.objects.filter(Q(admin_id=request.user.id) | Q(members__user=request.user)).values_list('id', flat=True).distinct()
           

            # Get all members of those teams
            team_members = TeamMember.objects.filter(team_id__in=team_ids)
           
            for tm in team_members:
                print(f" - {tm.user.username} (Team: {tm.team.name})")

            # Extract user objects
            users = [tm.user for tm in team_members]

            serializer = SimpleUserSerializer(users, many=True)
            return Response({'members': serializer.data}, status=status.HTTP_200_OK)

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)