from rest_framework import serializers
from djoser.serializers import UserCreateSerializer as BaseUserCreateSerializer
from djoser.serializers import UserSerializer as BaseUserSerializer
from .models import CustomUser


class CustomUserCreateSerializer(BaseUserCreateSerializer):
    """
    Custom serializer for user registration.
    Sets is_active=False by default so users must activate via email.
    """
    
    class Meta(BaseUserCreateSerializer.Meta):
        model = CustomUser
        fields = ('id', 'email', 'password', 're_password', 'first_name', 'last_name')
    
    def create(self, validated_data):
        """
        Override create to ensure is_active=False for email/password registrations.
        Social auth users will have is_active=True set via pipeline.
        """
        # Remove re_password as it's only for validation
        validated_data.pop('re_password', None)
        
        # Create user with is_active=False
        user = CustomUser.objects.create_user(
            email=validated_data['email'],
            password=validated_data['password'],
            first_name=validated_data.get('first_name', ''),
            last_name=validated_data.get('last_name', ''),
            is_active=False  # Requires email activation
        )
        return user


class CustomUserSerializer(BaseUserSerializer):
    """
    Serializer for user details.
    Used for current user endpoint and user profile.
    """
    
    class Meta(BaseUserSerializer.Meta):
        model = CustomUser
        fields = ('id', 'email', 'first_name', 'last_name', 'is_active', 'date_joined')
        read_only_fields = ('id', 'email', 'is_active', 'date_joined')


class SocialLoginSerializer(serializers.Serializer):
    """
    Serializer for social authentication.
    Accepts provider name and access_token from frontend.
    """
    provider = serializers.ChoiceField(
        choices=['google-oauth2', 'github', 'facebook'],
        help_text="Social auth provider name"
    )
    access_token = serializers.CharField(
        help_text="Access token from the social provider"
    )
    id_token = serializers.CharField(
        required=False,
        allow_blank=True,
        help_text="ID token (optional, used by some providers like Google)"
    )
    
    def validate_provider(self, value):
        """Validate that the provider is supported."""
        valid_providers = ['google-oauth2', 'github', 'facebook']
        if value not in valid_providers:
            raise serializers.ValidationError(
                f"Invalid provider. Must be one of: {', '.join(valid_providers)}"
            )
        return value

