# =============================================================
# pieteikumi/serializers.py
# =============================================================

from rest_framework import serializers
from .models import Pieteikums


class PieteikumsSerializer(serializers.ModelSerializer):
    """
    Lasīšanas serializators — React sarakstam un detaļām.
    Tulko lauku nosaukumus angliski priekš Frontend.
    """
    id             = serializers.IntegerField(read_only=True)
    title          = serializers.CharField(source='nosaukums',       read_only=True)
    type           = serializers.CharField(source='tips',            read_only=True)
    type_display   = serializers.CharField(source='get_tips_display', read_only=True)
    description    = serializers.CharField(source='apraksts',        read_only=True)
    budget         = serializers.CharField(source='budzets',         read_only=True)
    deadline       = serializers.CharField(source='termins',         read_only=True)
    status         = serializers.CharField(source='statuss',         read_only=True)
    status_display = serializers.CharField(source='get_statuss_display', read_only=True)
    admin_comment  = serializers.CharField(source='admin_komentars', read_only=True)
    submitted_by   = serializers.SerializerMethodField()
    created_at     = serializers.DateTimeField(source='izveidots',   read_only=True, format="%Y-%m-%d %H:%M")

    class Meta:
        model  = Pieteikums
        fields = [
            'id', 'title', 'type', 'type_display',
            'description', 'budget', 'deadline',
            'status', 'status_display', 'admin_comment',
            'submitted_by', 'created_at',
        ]

    def get_submitted_by(self, obj):
        u = obj.iesniedzejs
        return getattr(u, 'full_name', u.email) if u else '—'


class PieteikumsCreateSerializer(serializers.ModelSerializer):
    """
    Rakstīšanas serializators — validē un saglabā jaunu pieteikumu.
    """
    nosaukums = serializers.CharField(max_length=200)
    tips      = serializers.ChoiceField(choices=Pieteikums.TIPS_CHOICES)
    apraksts  = serializers.CharField(min_length=20)
    budzets   = serializers.CharField(max_length=100, required=False, allow_blank=True)
    termins   = serializers.CharField(max_length=100, required=False, allow_blank=True)

    class Meta:
        model  = Pieteikums
        fields = ['nosaukums', 'tips', 'apraksts', 'budzets', 'termins']
        
        # =============================================================
# MAILBOX (SAZIŅAS) SERIALIZERS — DROŠĪBA uzlabota
# =============================================================
from .models import Message
import re

class MessageSerializer(serializers.ModelSerializer):
    sender_is_admin = serializers.SerializerMethodField()
    sender_name = serializers.SerializerMethodField()
    sender_id = serializers.SerializerMethodField()
    # DROŠĪBA (HIGH-02): Satura validācija
    content = serializers.CharField(max_length=5000)

    class Meta:
        model = Message
        fields = ['id', 'sender_id', 'sender_is_admin', 'sender_name', 'content', 'created_at']
        # DROŠĪBA (HIGH-04): client un sender raw ID nav atklāti
        read_only_fields = ['id', 'sender_id', 'sender_is_admin', 'sender_name', 'created_at']

    def get_sender_is_admin(self, obj):
        return obj.sender.is_staff or obj.sender.is_superuser

    def get_sender_name(self, obj):
        return getattr(obj.sender, 'full_name', obj.sender.email)

    def get_sender_id(self, obj):
        return obj.sender_id

    def validate_content(self, value):
        """DROŠĪBA (HIGH-02): Notīra HTML tagus no ziņas satura."""
        # Noņemam HTML tagus
        cleaned = re.sub(r'<[^>]+>', '', value)
        # Noņemam arī script saturu
        cleaned = re.sub(r'javascript:', '', cleaned, flags=re.IGNORECASE)
        return cleaned.strip()

