from rest_framework import serializers
from .models import Company, OrgProfile, Department, Director


class CompanySerializer(serializers.ModelSerializer):
    """Serializer for Company model."""
    created_by_name = serializers.SerializerMethodField()
    logo_url = serializers.SerializerMethodField()

    class Meta:
        model = Company
        fields = [
            "id", "name", "abbreviation", "slug", "legal_name", "company_type", "donor_category",
            "industry",
            "website", "email", "phone", "address", "city", "country", "tax_id",
            "pic", "pic_title",
            "logo", "logo_url", "description", "notes", "tags", "created_by",
            "created_by_name", "created_at", "updated_at"
        ]
        read_only_fields = ["id", "logo_url", "created_at", "updated_at"]

    def get_created_by_name(self, obj):
        if obj.created_by:
            return obj.created_by.get_full_name() or obj.created_by.username
        return None

    def get_logo_url(self, obj):
        if not obj.logo:
            return None
        request = self.context.get("request")
        url = obj.logo.url
        return request.build_absolute_uri(url) if request else url


class OrgProfileSerializer(serializers.ModelSerializer):
    """Serializer for the organization profile singleton."""
    logo_url = serializers.SerializerMethodField()

    class Meta:
        model = OrgProfile
        fields = [
            "id", "name", "legal_name", "tagline", "logo", "logo_url",
            "email", "phone", "website", "address", "city", "country",
            "latitude", "longitude",
            "tax_id", "description", "created_at", "updated_at",
        ]
        read_only_fields = ["id", "logo_url", "created_at", "updated_at"]

    def get_logo_url(self, obj):
        if not obj.logo:
            return None
        request = self.context.get("request")
        url = obj.logo.url
        return request.build_absolute_uri(url) if request else url


class DepartmentSerializer(serializers.ModelSerializer):
    """Serializer for internal Department records."""
    head_name = serializers.SerializerMethodField()
    parent_name = serializers.SerializerMethodField()
    employee_count = serializers.SerializerMethodField()

    class Meta:
        model = Department
        fields = [
            "id", "name", "code", "description", "parent", "parent_name",
            "head", "head_name", "employee_count", "created_at", "updated_at",
        ]
        read_only_fields = ["id", "parent_name", "head_name", "employee_count", "created_at", "updated_at"]

    def get_head_name(self, obj):
        if obj.head_id and obj.head and obj.head.user_id:
            return obj.head.user.get_full_name() or obj.head.user.username
        return None

    def get_parent_name(self, obj):
        return obj.parent.name if obj.parent_id else None

    def get_employee_count(self, obj):
        counts = self.context.get("dept_counts")
        if counts is not None:
            return counts.get(obj.name, 0)
        from apps.hr.models import Employee
        return Employee.objects.filter(department=obj.name).count()


class DirectorSerializer(serializers.ModelSerializer):
    """Serializer for Director records. Always linked to an Employee."""
    employee_name = serializers.SerializerMethodField()
    employee_email = serializers.SerializerMethodField()
    employee_phone = serializers.SerializerMethodField()
    employee_position = serializers.CharField(source="employee.position", read_only=True)
    employee_department = serializers.CharField(source="employee.department", read_only=True)
    photo_url = serializers.SerializerMethodField()

    class Meta:
        model = Director
        fields = [
            "id", "employee", "employee_name", "employee_email",
            "employee_phone", "employee_position", "employee_department",
            "photo_url", "title", "bio",
            "order", "is_active", "created_at", "updated_at",
        ]
        read_only_fields = [
            "id", "employee_name", "employee_email", "employee_phone",
            "employee_position", "employee_department", "photo_url",
            "created_at", "updated_at",
        ]

    def get_employee_name(self, obj):
        if obj.employee_id and obj.employee.user_id:
            return obj.employee.user.get_full_name() or obj.employee.user.username
        return None

    def get_employee_email(self, obj):
        return obj.employee.user.email if obj.employee_id and obj.employee.user_id else None

    def get_employee_phone(self, obj):
        return getattr(obj.employee.user, "phone", "") if obj.employee_id and obj.employee.user_id else ""

    def get_photo_url(self, obj):
        if not obj.employee_id or not obj.employee.user_id:
            return None
        contact = getattr(obj.employee.user, "contact_profile", None)
        if contact and contact.avatar:
            request = self.context.get("request")
            url = contact.avatar.url
            return request.build_absolute_uri(url) if request else url
        return None
