from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import RegistrationDomainRule, RegistrationRestrictionSetting, SMTPSetting
from apps.events.models import Skill

User = get_user_model()

class SkillSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Skill
        fields = ['id', 'name', 'description', 'color']

class UserSerializer(serializers.ModelSerializer):
    skills = SkillSimpleSerializer(many=True, read_only=True)
    skill_ids = serializers.PrimaryKeyRelatedField(
        queryset=Skill.objects.all(), many=True, write_only=True, required=False, source='skills'
    )

    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'display_name', 'is_admin_user', 'is_staff', 'is_superuser', 'is_approved', 'is_email_verified', 'is_active', 'skills', 'skill_ids']
        read_only_fields = ['id', 'is_staff', 'is_superuser', 'is_approved', 'is_email_verified']

class AdminUserSerializer(serializers.ModelSerializer):
    skills = SkillSimpleSerializer(many=True, read_only=True)
    skill_ids = serializers.PrimaryKeyRelatedField(
        queryset=Skill.objects.all(), many=True, write_only=True, required=False, source='skills'
    )

    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'display_name', 'is_admin_user', 'is_staff', 'is_superuser', 'is_approved', 'is_email_verified', 'is_active', 'skills', 'skill_ids', 'date_joined']
        read_only_fields = ['id', 'date_joined']

class RegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, min_length=6)

    class Meta:
        model = User
        fields = ['username', 'email', 'password', 'display_name']

    def validate_email(self, value):
        email = value.strip().lower()
        setting = RegistrationRestrictionSetting.get_solo()
        if setting.is_restriction_enabled:
            allowed_rules = RegistrationDomainRule.objects.filter(is_active=True)
            if allowed_rules.exists():
                email_domain = email.split('@')[-1] if '@' in email else ''
                matched = False
                for rule in allowed_rules:
                    clean_rule = rule.domain.lstrip('@').lower()
                    if email_domain == clean_rule or email_domain.endswith('.' + clean_rule):
                        matched = True
                        break
                if not matched:
                    domains_list = ", ".join([r.domain for r in allowed_rules])
                    raise serializers.ValidationError(
                        f"Registrierungen sind derzeit nur für folgende E-Mail-Domains erlaubt: {domains_list}"
                    )
        return email

    def create(self, validated_data):
        display_name = validated_data.get('display_name', '') or validated_data['username']
        user = User.objects.create_user(
            username=validated_data['username'],
            email=validated_data['email'],
            password=validated_data['password'],
            display_name=display_name
        )
        return user

class RegistrationDomainRuleSerializer(serializers.ModelSerializer):
    class Meta:
        model = RegistrationDomainRule
        fields = ['id', 'domain', 'is_active', 'created_at']

class RegistrationRestrictionSettingSerializer(serializers.ModelSerializer):
    class Meta:
        model = RegistrationRestrictionSetting
        fields = ['is_restriction_enabled', 'require_admin_approval', 'require_email_verification']

class SMTPSettingSerializer(serializers.ModelSerializer):
    class Meta:
        model = SMTPSetting
        fields = ['is_active', 'host', 'port', 'username', 'password', 'use_tls', 'use_ssl', 'from_email']
