from rest_framework import serializers

from .models import (
    DayOff,
    ExtraOff,
    EmployeeRole,
    Department,
    EmployeeDT,
    EmployeeAccount,
    BankAccount,
    Payroll,
    Message,
    Target,
    EMP_check_in_check_out,
    DailyTask,
    AttendanceEmp,
    EmployeeDocument,
    CandidateEducation,
    CandidateExperience,
    CandidateCompensation,
    CandidateBGV,
)


# ============================================================
# DAY OFF
# ============================================================

class DayOffSerializer(serializers.ModelSerializer):
    class Meta:
        model = DayOff
        fields = "__all__"


# ============================================================
# EXTRA OFF
# ============================================================

class ExtraOffSerializer(serializers.ModelSerializer):
    class Meta:
        model = ExtraOff
        fields = "__all__"


# ============================================================
# EMPLOYEE ROLE
# ============================================================

class EmployeeRoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = EmployeeRole
        fields = "__all__"
        read_only_fields = ["company","created_at", "updated_at"]


# ============================================================
# ADDITIVE: DEPARTMENT
# ============================================================

class DepartmentSerializer(serializers.ModelSerializer):

    employee_count = serializers.SerializerMethodField()

    class Meta:
        model = Department
        fields = [
            "id",
            "company",
            "name",
            "code",
            "description",
            "is_active",
            "employee_count",
            "created_at",
            "updated_at",
        ]
        read_only_fields = ["company", "created_at", "updated_at"]

    def get_employee_count(self, obj):
        return obj.employees.count()


# ============================================================
# EMPLOYEE - FULL MODEL
# ============================================================

class EmployeeDTSerializer(serializers.ModelSerializer):
    """
    Full EmployeeDT serializer.

    All existing EmployeeDT fields are exposed so the expanded
    employee/candidate model can be used without dropping any
    previous fields.
    """

    class Meta:
        model = EmployeeDT
        fields = "__all__"
        read_only_fields = [
            "employee_code",
            "created_at",
            "updated_at",
            "candidate_id",
            "application_submitted_at",
        ]


# ============================================================
# EMPLOYEE ACCOUNT
# ============================================================

class EmployeeAccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = EmployeeAccount
        fields = "__all__"
        read_only_fields = [
            "last_login",
            "failed_login_attempts",
            "created_at",
            "updated_at",
        ]


# ============================================================
# BANK ACCOUNT
# ============================================================

class BankAccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = BankAccount
        fields = "__all__"
        read_only_fields = [
            "created_at",
            "deactivated_at",
        ]


# ============================================================
# EMPLOYEE DOCUMENT
# ============================================================

class EmployeeDocumentSerializer(serializers.ModelSerializer):
    """
    Generic employee document.

    company is read-only and is synchronized from employee.company
    in the model save() method.
    """

    class Meta:
        model = EmployeeDocument
        fields = "__all__"
        read_only_fields = [
            "company",
            "uploaded_at",
            "updated_at",
        ]


# ============================================================
# CANDIDATE EDUCATION
# ============================================================

class CandidateEducationSerializer(serializers.ModelSerializer):
    class Meta:
        model = CandidateEducation
        fields = "__all__"
        read_only_fields = ["created_at"]


# ============================================================
# CANDIDATE EXPERIENCE
# ============================================================

class CandidateExperienceSerializer(serializers.ModelSerializer):
    class Meta:
        model = CandidateExperience
        fields = "__all__"
        read_only_fields = ["created_at"]


# ============================================================
# CANDIDATE COMPENSATION
# ============================================================

class CandidateCompensationSerializer(serializers.ModelSerializer):
    class Meta:
        model = CandidateCompensation
        fields = "__all__"
        read_only_fields = [
            "created_at",
            "updated_at",
        ]


# ============================================================
# CANDIDATE BACKGROUND VERIFICATION
# ============================================================

class CandidateBGVSerializer(serializers.ModelSerializer):
    class Meta:
        model = CandidateBGV
        fields = "__all__"
        read_only_fields = [
            "created_at",
            "updated_at",
        ]


# ============================================================
# PAYROLL
# ============================================================

class PayrollSerializer(serializers.ModelSerializer):
    class Meta:
        model = Payroll
        fields = "__all__"
        read_only_fields = ["created_at"]


# ============================================================
# MESSAGE
# ============================================================

class MessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Message
        fields = "__all__"
        read_only_fields = ["timestamp"]


# ============================================================
# TARGET
# ============================================================

class TargetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Target
        fields = "__all__"


# ============================================================
# EMPLOYEE CHECK IN / CHECK OUT
# ============================================================

class EmployeeCheckInOutSerializer(serializers.ModelSerializer):
    class Meta:
        model = EMP_check_in_check_out
        fields = "__all__"


# ============================================================
# DAILY TASK
# ============================================================

class DailyTaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = DailyTask
        fields = "__all__"
        read_only_fields = ["created_at"]


# ============================================================
# ATTENDANCE
# ============================================================

class AttendanceEmpSerializer(serializers.ModelSerializer):
    class Meta:
        model = AttendanceEmp
        fields = "__all__"
        read_only_fields = ["created_at"]


# ============================================================
# EMPLOYEE CRUD SERIALIZER
# ============================================================

class EmployeeCRUDSerializer(serializers.ModelSerializer):
    """
    Full employee-management serializer.

    Company is never accepted from the client. The view sets it
    from the authenticated Admin/HR user's company.

    Password is WRITE-ONLY here (never returned). It is still
    accepted because the existing project uses EmployeeDT.password
    for employee login. If you want
    credential creation separated from employee creation later,
    EmployeeAccount can be used for that workflow.
    """

    company_id = serializers.CharField(
        source="company.company_id",
        read_only=True,
    )

    documents = EmployeeDocumentSerializer(
        many=True,
        read_only=True,
    )

    educational_history = CandidateEducationSerializer(
        many=True,
        read_only=True,
    )

    professional_experience = CandidateExperienceSerializer(
        many=True,
        read_only=True,
    )

    compensation_package = CandidateCompensationSerializer(
        read_only=True,
    )

    bgv = CandidateBGVSerializer(
        read_only=True,
    )

    bank_accounts = BankAccountSerializer(
        many=True,
        read_only=True,
    )

    class Meta:
        model = EmployeeDT
        fields = [
            "id",
            "employee_code",
            "candidate_id",
            "company_id",
            "is_active",

            # Shift / identity
            "Work_sift",
            "Employ_check_id",
            "check_st",
            "verify_image",
            "profile_image",

            # Basic
            "name",
            "email",
            "password",
            "phone_number",
            "verify_code",

            # Personal
            "image",
            "Date_of_Birth",
            "Gender",
            "Blood_Group",
            "Marital_Status",
            "Marriage_Anniversary",
            "Personal_Email",
            "Alternate_Phone_Number",
            "Current_Address",
            "Permanent_Address",
            "House_Type",
            "Staying_at_Current_Residence_Since",
            "Living_in_Current_City_Since",

            # Work
            "Date_of_Joining",
            "Basic_Salary",
            "Overtime_Rate",
            "Work_hours",
            "PF_Percentage",
            "TDS_Percentage",
            "ESI_Percentage",
            "saturday_policy",

            # Statutory
            "aadhaar_number",
            "pan_number",
            "pf_number",
            "esi_number",

            # Employment
            "Probation_Period",
            "Employee_Type",
            "Work_Location",
            "Employee_Status",
            "Work_Experience",
            "Designation",
            "Job_Title",
            "Department",
            "Sub_Department",
            "WORK_HISTORY",
            "Resignation_Date",
            "Resignation_Status",
            "Notice_Period",
            "Last_Working_Day",

            # Team / old education / family
            "team_Name",
            "team_type",
            "team_Department",
            "team_Designation",
            "EDUCATIONAL_INFO",
            "Family_Name",
            "Family_Relationship",
            "Family_Phone_Number",

            # Candidate
            "applied_position",
            "candidate_source",
            "recruiter_name",
            "expected_joining_date",
            "candidate_status",
            "same_as_current_address",
            "application_submitted",
            "application_submitted_at",
            "Current_Notice_Period",

            # Candidate documents kept on EmployeeDT
            "resume",
            "aadhaar_id_proof",
            "pan_card",
            "address_proof",
            "passport_photo",
            "educational_certificates",
            "key_certifications",

            # Existing M2M
            "work_week",
            "extra_off",

            # Related read-only information
            "documents",
            "educational_history",
            "professional_experience",
            "compensation_package",
            "bgv",
            "bank_accounts",

            "created_at",
            "updated_at",
        ]

        read_only_fields = [
            "id",
            "employee_code",
            "candidate_id",
            "company_id",
            "application_submitted_at",
            "created_at",
            "updated_at",
            "documents",
            "educational_history",
            "professional_experience",
            "compensation_package",
            "bgv",
            "bank_accounts",
        ]

        # HR/Admin can SET a password here (create / update) but it is
        # never returned by list / detail responses.
        extra_kwargs = {
            "password": {"write_only": True},
        }

    def validate_email(self, value):
        if not value:
            return value

        request = self.context.get("request")

        from .employee_crud_permissions import resolve_company_for_user

        company = (
            resolve_company_for_user(getattr(request, "user", None))
            if request
            else None
        )

        if company is None:
            return value

        qs = EmployeeDT.objects.filter(
            company=company,
            email__iexact=value,
        )

        if self.instance is not None:
            qs = qs.exclude(pk=self.instance.pk)

        if qs.exists():
            raise serializers.ValidationError(
                "An employee with this email already exists in your company."
            )

        return value

    def validate(self, attrs):
        attrs.pop("company", None)
        return attrs
 

# ============================================================
# ADDITIVE: Employee self-service profile (restricted fields)
# Personal-info only - salary, statutory numbers, role, and
# employment-status fields are intentionally excluded so a
# plain employee can't grant themselves a raise or change their
# own designation/active-status through this endpoint. Admin/HR
# still edit everything via EmployeeCRUDSerializer.
# ============================================================

class EmployeeSelfProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = EmployeeDT
        fields = [
            "id",
            "employee_code",
            "name",
            "email",
            "phone_number",
            "profile_image",
            "image",
            "Date_of_Birth",
            "Gender",
            "Blood_Group",
            "Marital_Status",
            "Marriage_Anniversary",
            "Personal_Email",
            "Alternate_Phone_Number",
            "Current_Address",
            "Permanent_Address",
            "House_Type",
            "Family_Name",
            "Family_Relationship",
            "Family_Phone_Number",
        ]
        read_only_fields = [
            "id",
            "employee_code",
        ]


