from rest_framework import serializers

from apps.accounts.serializers import UserSerializer

from .models import Ticket


class TicketSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    category_display = serializers.CharField(source="get_category_display", read_only=True)
    status_display = serializers.CharField(source="get_status_display", read_only=True)

    class Meta:
        model = Ticket
        fields = [
            "id",
            "user",
            "category",
            "category_display",
            "subject",
            "message",
            "email",
            "status",
            "status_display",
            "created_at",
            "updated_at",
        ]
        read_only_fields = ["id", "status", "created_at", "updated_at", "user"]

    def validate(self, data):
        # Ensure email is provided if user is anonymous
        request = self.context.get("request")
        if request and not request.user.is_authenticated and not data.get("email"):
            raise serializers.ValidationError({"email": "Email is required for guests."})
        return data


class ReportSerializer(serializers.ModelSerializer):
    """Serializer for Report model."""

    reporter_username = serializers.CharField(source="reporter.username", read_only=True, allow_null=True)
    resolved_by_username = serializers.CharField(source="resolved_by.username", read_only=True, allow_null=True)
    report_type_display = serializers.CharField(source="get_report_type_display", read_only=True)
    status_display = serializers.CharField(source="get_status_display", read_only=True)
    content_type_name = serializers.CharField(source="content_type.model", read_only=True)
    is_resolved = serializers.BooleanField(read_only=True)

    class Meta:
        from .models import Report

        model = Report
        fields = [
            "id",
            "reporter",
            "reporter_username",
            "content_type",
            "content_type_name",
            "object_id",
            "report_type",
            "report_type_display",
            "reason",
            "status",
            "status_display",
            "resolved_at",
            "resolved_by",
            "resolved_by_username",
            "resolution_notes",
            "is_resolved",
            "created_at",
            "updated_at",
        ]
        read_only_fields = [
            "id",
            "reporter",
            "resolved_at",
            "resolved_by",
            "created_at",
            "updated_at",
        ]


class ReportCreateSerializer(serializers.ModelSerializer):
    """Serializer for creating reports with entity type as string."""

    entity_type = serializers.CharField(write_only=True, help_text="Type of entity: park, ride, review, etc.")
    entity_id = serializers.CharField(write_only=True, help_text="ID of the entity being reported")

    class Meta:
        from .models import Report

        model = Report
        fields = [
            "entity_type",
            "entity_id",
            "report_type",
            "reason",
        ]

    def validate(self, data):
        from django.contrib.contenttypes.models import ContentType

        entity_type = data.pop("entity_type")
        entity_id = data.pop("entity_id")

        # Map common entity types to app.model
        type_mapping = {
            "park": ("parks", "park"),
            "ride": ("rides", "ride"),
            "review": ("reviews", "review"),
            "user": ("accounts", "user"),
        }

        if entity_type in type_mapping:
            app_label, model_name = type_mapping[entity_type]
        else:
            # Try to parse as app.model
            parts = entity_type.split(".")
            if len(parts) != 2:
                raise serializers.ValidationError(
                    {"entity_type": f"Unknown entity type: {entity_type}. Use 'park', 'ride', 'review', or 'app.model'."}
                )
            app_label, model_name = parts

        try:
            content_type = ContentType.objects.get(app_label=app_label, model=model_name)
        except ContentType.DoesNotExist:
            raise serializers.ValidationError({"entity_type": f"Unknown entity type: {entity_type}"})

        data["content_type"] = content_type
        data["object_id"] = entity_id
        return data


class ReportResolveSerializer(serializers.Serializer):
    """Serializer for resolving reports."""

    status = serializers.ChoiceField(
        choices=[("resolved", "Resolved"), ("dismissed", "Dismissed")],
        default="resolved",
    )
    notes = serializers.CharField(required=False, allow_blank=True)

