import graphene
from graphene_django import DjangoObjectType
from django.contrib.auth import get_user_model
from ..models import Team as TeamModel, TeamMember as TeamMemberModel
from ..permissions import require_scopes

UserModel = get_user_model()

class User(DjangoObjectType):
    id = graphene.String()
    firstName = graphene.String()
    lastName = graphene.String()
    phone = graphene.String()
    avatarId = graphene.String()
    createdAt = graphene.String()
    
    class Meta:
        model = UserModel
        fields = ('username', 'first_name', 'last_name', 'email')
    
    def resolve_id(self, info):
        if hasattr(self, 'profile') and self.profile:
            return self.profile.logto_id
        return self.username
    
    def resolve_firstName(self, info):
        return self.first_name
        
    def resolve_lastName(self, info):
        return self.last_name
        
    def resolve_phone(self, info):
        return getattr(self.profile, 'phone', None)
        
    def resolve_avatarId(self, info):
        return getattr(self.profile, 'avatar_id', None)

    def resolve_createdAt(self, info):
        return self.date_joined.isoformat() if self.date_joined else None

class TeamMember(DjangoObjectType):
    user = graphene.Field(User)
    joinedAt = graphene.String()
    
    class Meta:
        model = TeamMemberModel
        fields = ('role', 'joined_at')
    
    def resolve_user(self, info):
        return self.user
    
    def resolve_joinedAt(self, info):
        return self.joined_at.isoformat() if self.joined_at else None

class Team(DjangoObjectType):
    id = graphene.String()
    ownerId = graphene.String()
    members = graphene.List(TeamMember)
    
    class Meta:
        model = TeamModel
        fields = ('uuid', 'name', 'status', 'logto_org_id', 'owner', 'created_at', 'updated_at')
    
    def resolve_id(self, info):
        return self.uuid

    def resolve_ownerId(self, info):
        if self.owner and hasattr(self.owner, 'profile'):
            return self.owner.profile.logto_id
        return self.owner.username if self.owner else None
    
    def resolve_members(self, info):
        return self.members.all()

class TeamQuery(graphene.ObjectType):
    team = graphene.Field(Team)
    getTeam = graphene.Field(Team, teamId=graphene.String(required=True))
    team_members = graphene.List(TeamMember)
    
    @require_scopes("read:teams")
    def resolve_team(self, info):
        # Получаем organization_id из Team Access Token
        org_id = getattr(info.context, 'organization_id', None)
        if not org_id:
            return None

        try:
            return TeamModel.objects.get(logto_org_id=org_id)
        except TeamModel.DoesNotExist:
            return None

    @require_scopes("read:teams")
    def resolve_getTeam(self, info, teamId):
        # Получаем конкретную команду по ID
        try:
            return TeamModel.objects.get(uuid=teamId)
        except TeamModel.DoesNotExist:
            return None

    @require_scopes("read:teams")
    def resolve_team_members(self, info):
        # Получаем участников команды
        org_id = getattr(info.context, 'organization_id', None)
        if not org_id:
            return []

        try:
            team = TeamModel.objects.get(logto_org_id=org_id)
            return team.members.all()
        except TeamModel.DoesNotExist:
            return []

class InviteMemberInput(graphene.InputObjectType):
    email = graphene.String(required=True)
    role = graphene.String()

class InviteMemberMutation(graphene.Mutation):
    class Arguments:
        input = InviteMemberInput(required=True)

    success = graphene.Boolean()
    message = graphene.String()

    @require_scopes("invite:members")
    def mutate(self, info, input):
        # Проверяем права - только owner может приглашать
        org_id = getattr(info.context, 'organization_id', None)
        user_id = getattr(info.context, 'user_id', None)
        
        if not org_id or not user_id:
            return InviteMemberMutation(success=False, message="Недостаточно прав")
        
        try:
            team = TeamModel.objects.get(logto_org_id=org_id)
            
            # Проверяем что пользователь - owner команды
            if not team.owner:
                return InviteMemberMutation(success=False, message="Только owner может приглашать")
            owner_identifier = team.owner.profile.logto_id if hasattr(team.owner, 'profile') and team.owner.profile else team.owner.username
            if owner_identifier != user_id:
                return InviteMemberMutation(success=False, message="Только owner может приглашать")
            
            # TODO: Логика отправки приглашения
            return InviteMemberMutation(success=True, message="Приглашение отправлено")
            
        except TeamModel.DoesNotExist:
            return InviteMemberMutation(success=False, message="Команда не найдена")

class TeamMutation(graphene.ObjectType):
    invite_member = InviteMemberMutation.Field()

team_schema = graphene.Schema(query=TeamQuery, mutation=TeamMutation)
