from rest_framework import serializers
from django.db import transaction
from django.contrib.auth.models import User
from core.models import Bookmark, Team, TeamMembership, BookmarkShare, Extraction, Summary
from taggit.serializers import TagListSerializerField, TaggitSerializer

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email']

class TeamSerializer(serializers.ModelSerializer):
    class Meta:
        model = Team
        fields = ['id', 'name', 'description', 'created_at']

class ExtractionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Extraction
        fields = ['content_text', 'extracted_at']

class SummarySerializer(serializers.ModelSerializer):
    class Meta:
        model = Summary
        fields = ['content', 'generated_at']

class BookmarkSerializer(TaggitSerializer, serializers.ModelSerializer):
    tags = TagListSerializerField(required=False)
    summary = SummarySerializer(read_only=True)
    
    class Meta:
        model = Bookmark
        fields = ['id', 'url', 'title', 'notes', 'is_favorite', 'tags', 'summary', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']

    def create(self, validated_data):
        user = self.context['request'].user
        tags = validated_data.pop('tags', [])
        with transaction.atomic():
            bookmark = Bookmark.objects.create(user=user, **validated_data)
            bookmark.tags.set(tags)
        return bookmark

    def update(self, instance, validated_data):
        tags = validated_data.pop('tags', None)
        with transaction.atomic():
            instance = super().update(instance, validated_data)
            if tags is not None:
                instance.tags.set(tags)
        return instance

class BookmarkDetailSerializer(BookmarkSerializer):
    extraction = ExtractionSerializer(read_only=True)
    
    class Meta(BookmarkSerializer.Meta):
        fields = BookmarkSerializer.Meta.fields + ['extraction']
