from rest_framework import serializers
from apps.companies.models import Company
from django.contrib.auth import get_user_model
from apps.permissions.models import UserCompanyRole
from apps.userprofile.serializers import UserProfileSerializer
from apps.core.utils.generate_password_util import generate_secure_password

User = get_user_model()


class CreateUserSerializer(serializers.ModelSerializer):
    company_ids = serializers.ListField(
        child=serializers.IntegerField(),
        required=True,
        write_only=True,
        help_text="List of company IDs to assign user to"
    )

    class Meta:
        model = User
        fields = ['email', 'username', 'is_active', 'is_available', 'company_ids']
        extra_kwargs = {
            'username': {'required': False, 'allow_blank': True}
        }
        # Removed password from fields since system will generate it
    
    def to_internal_value(self, data):
        """Override to handle profile[field_name] format"""
        # Extract profile data from the request
        profile_data = {}
        profile_fields = ['first_name', 'last_name', 'phone_number', 'image']
        
        for field in profile_fields:
            profile_key = f'profile[{field}]'
            if profile_key in data:
                profile_data[field] = data[profile_key]
        
        # Store profile data for later use
        self._profile_data = profile_data
        
        # Remove profile fields from data before validation
        data_copy = data.copy()
        for field in profile_fields:
            profile_key = f'profile[{field}]'
            if profile_key in data_copy:
                del data_copy[profile_key]
        
        return super().to_internal_value(data_copy)

    def create(self, validated_data):
        generated_password = generate_secure_password(12)

        validated_data['password'] = generated_password
        profile_data = getattr(self, '_profile_data', {})
        company_ids = validated_data.pop('company_ids', [])
        companies = []

        if company_ids:
            try:
                companies = Company.objects.filter(id__in=company_ids, is_active=True)
                # Validate all companies exist
                if len(companies) != len(company_ids):
                    found_ids = [c.id for c in companies]
                    missing_ids = [cid for cid in company_ids if cid not in found_ids]
                    raise serializers.ValidationError({
                        "company_ids": f"Companies with IDs {missing_ids} not found or inactive"
                    })
            except Company.DoesNotExist:
                raise serializers.ValidationError({"company_ids": "Invalid company IDs provided"})

        # Remove fields that UserManager.create_user doesn't accept
        validated_data.pop('is_active', True)
        is_available = validated_data.pop('is_available', True)

        user = User.objects.create_user(**validated_data, companies=companies)
        user.is_active = True #user will be active by default
        user.is_available = is_available
        user.save()

        if companies:
            for company in companies:
                UserCompanyRole.objects.create(
                    user=user,
                    company=company,
                    role=None  # No role assigned initially
                )

        if profile_data:
            profile_serializer = UserProfileSerializer(data=profile_data)
            if profile_serializer.is_valid():
                profile_serializer.save(user=user)
            else:
                raise serializers.ValidationError({'profile': profile_serializer.errors})

        user._generated_password = generated_password

        return user