from rest_framework import serializers
from django.contrib.auth import authenticate
from .models import User, Role, SiteConfiguration


class UserSerializer(serializers.ModelSerializer):
    initials = serializers.ReadOnlyField()
    is_superuser = serializers.BooleanField(read_only=True)
    roles = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = [
            'id', 'email', 'full_name', 'roles', 'department',
            'profile_photo', 'is_active', 'joined_date',
            'theme_preference', 'initials', 'created_at', 'is_superuser'
        ]
        read_only_fields = ['id', 'created_at', 'initials', 'is_superuser']

    def get_roles(self, obj):
        roles = list(obj.roles.values_list('name', flat=True))
        if obj.is_superuser and 'CEO' not in roles:
            roles.append('CEO')
        return roles


class UserDetailSerializer(serializers.ModelSerializer):
    """Full detail — includes salary info for authorized roles"""
    initials = serializers.ReadOnlyField()
    hourly_rate = serializers.ReadOnlyField()
    is_superuser = serializers.BooleanField(read_only=True)
    roles = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = [
            'id', 'email', 'full_name', 'roles', 'department',
            'salary_pkr', 'hourly_rate', 'profile_photo',
            'is_active', 'joined_date', 'force_password_change',
            'theme_preference', 'email_notifications',
            'initials', 'created_at', 'updated_at', 'is_superuser'
        ]
        read_only_fields = ['id', 'hourly_rate', 'created_at', 'updated_at', 'initials', 'is_superuser']

    def get_roles(self, obj):
        roles = list(obj.roles.values_list('name', flat=True))
        if obj.is_superuser and 'CEO' not in roles:
            roles.append('CEO')
        return roles


class UserCreateSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, min_length=8)
    roles = serializers.SlugRelatedField(
        many=True, slug_field='name', queryset=Role.objects.all()
    )

    class Meta:
        model = User
        fields = [
            'email', 'full_name', 'password', 'roles', 'department',
            'salary_pkr', 'profile_photo', 'joined_date'
        ]

    def create(self, validated_data):
        roles_data = validated_data.pop('roles', [])
        password = validated_data.pop('password')
        user = User(**validated_data)
        user.set_password(password)
        user.force_password_change = True
        user.save()
        user.roles.set(roles_data)
        return user


class UserUpdateSerializer(serializers.ModelSerializer):
    roles = serializers.SlugRelatedField(
        many=True, slug_field='name', queryset=Role.objects.all()
    )

    class Meta:
        model = User
        fields = [
            'full_name', 'roles', 'department', 'salary_pkr',
            'profile_photo', 'is_active', 'joined_date'
        ]


class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = serializers.CharField()

    def validate(self, data):
        user = authenticate(email=data['email'], password=data['password'])
        if user is None:
            raise serializers.ValidationError('Invalid email or password')
        if not user.is_active:
            raise serializers.ValidationError('Account is deactivated')
        data['user'] = user
        return data


class PasswordChangeSerializer(serializers.Serializer):
    old_password = serializers.CharField()
    new_password = serializers.CharField(min_length=8)
    confirm_password = serializers.CharField(min_length=8)

    def validate(self, data):
        if data['new_password'] != data['confirm_password']:
            raise serializers.ValidationError({'confirm_password': 'Passwords do not match'})
        return data


class ProfileSerializer(serializers.ModelSerializer):
    initials = serializers.ReadOnlyField()
    is_superuser = serializers.BooleanField(read_only=True)
    roles = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = [
            'id', 'email', 'full_name', 'roles', 'department',
            'profile_photo', 'theme_preference', 'email_notifications',
            'initials', 'force_password_change', 'is_superuser'
        ]
        read_only_fields = ['id', 'email', 'roles', 'department', 'initials', 'is_superuser']

    def get_roles(self, obj):
        roles = list(obj.roles.values_list('name', flat=True))
        if obj.is_superuser and 'CEO' not in roles:
            roles.append('CEO')
        return roles


class PasswordResetRequestSerializer(serializers.Serializer):
    email = serializers.EmailField()


class PasswordResetConfirmSerializer(serializers.Serializer):
    token = serializers.CharField()
    new_password = serializers.CharField(min_length=8)
    confirm_password = serializers.CharField(min_length=8)

    def validate(self, data):
        if data['new_password'] != data['confirm_password']:
            raise serializers.ValidationError({'confirm_password': 'Passwords do not match'})
        return data

class SiteConfigurationSerializer(serializers.ModelSerializer):
    class Meta:
        model = SiteConfiguration
        fields = ['site_name', 'site_logo', 'site_favicon', 'tagline', 'updated_at']
