from rest_framework.decorators import api_view, permission_classes
from rest_framework import serializers
from rest_framework.response import Response
from basic_info.models import Employee, Merchant


class MerchantSerializer(serializers.ModelSerializer):
    """商户信息序列化器"""
    type_display = serializers.CharField(source='get_type_display', read_only=True)
    
    class Meta:
        model = Merchant
        fields = [
            'id',
            'name',
            'type',
            'type_display',
            'area',
            'email',
            'mobile',
            'contact',
            'auto_complete_stock_change',
            'description',
        ]


class EmployeeSerializer(serializers.ModelSerializer):
    """员工信息序列化器（嵌套商户信息）"""
    job_type_display = serializers.CharField(source='get_job_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    merchant = MerchantSerializer(read_only=True)
    
    class Meta:
        model = Employee
        fields = [
            'id',
            'name',
            'job_type',
            'job_type_display',
            'mobile',
            'area',
            'status',
            'status_display',
            'description',
            'merchant',
        ]


class UserInfoSerializer(serializers.Serializer):
    """用户信息序列化器（嵌套员工和商户信息）"""
    username = serializers.CharField()
    email = serializers.EmailField()
    is_staff = serializers.BooleanField()
    employee = EmployeeSerializer()


@api_view(['GET'])
def user_info(request):
    """
    获取当前用户的基本信息（包含员工信息和商户信息）
    
    GET /api/v1/user-info/
    
    返回：
    - username: 用户名
    - email: 邮箱
    - is_staff: 是否为管理员
    - employee: 员工信息（包含 merchant 商户信息）
    """
    user = request.user
    
    # 验证用户必须登录且有员工身份
    if not user.is_authenticated or not hasattr(user, 'employee'):
        return Response({'error': 'Unauthorized'}, status=401)
    
    # 使用序列化器序列化数据
    serializer = UserInfoSerializer(user)
    return Response(serializer.data, status=200)