from rest_framework import serializers
from .models import Application

class ApplicationCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Application
        fields = ['job']

    def validate(self, data):
        request = self.context['request']
        if Application.objects.filter(job=data['job'], applicant=request.user).exists():
            raise serializers.ValidationError({'detail': '您已投递过该职位'})
        return data

    def create(self, validated_data):
        request = self.context['request']
        try:
            resume = request.user.resume
        except Exception:
            raise serializers.ValidationError(
                {'detail': '请先完善简历后再投递'}
            )
        if not resume.name:
            raise serializers.ValidationError(
                {'detail': '请先完善简历后再投递'}
            )
        return Application.objects.create(
            job=validated_data['job'],
            applicant=request.user,
            resume_snapshot=resume.to_snapshot(),
        )

class ApplicationSerializer(serializers.ModelSerializer):
    job_title = serializers.CharField(source='job.title', read_only=True)
    company_name = serializers.CharField(source='job.organization.name', read_only=True)

    class Meta:
        model = Application
        fields = ['id', 'job', 'job_title', 'company_name',
                  'resume_snapshot', 'status', 'note', 'applied_at']
        read_only_fields = ['resume_snapshot', 'applied_at']

class ApplicationStatusSerializer(serializers.ModelSerializer):
    """HR 更新状态"""
    class Meta:
        model = Application
        fields = ['status', 'note']
