from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from .models import Risk, Control, ResidualRisk, AuditLog, Incident


# ---------------------------------------------------------------------------
# ResidualRiskSerializer
# ---------------------------------------------------------------------------
class ResidualRiskSerializer(serializers.ModelSerializer):
    class Meta:
        model = ResidualRisk
        fields = [
            "id",
            "risk",
            "likelihood",
            "impact",
            "score",
            "level",
            "review_required",
        ]
        read_only_fields = ["score", "level"]


# ---------------------------------------------------------------------------
# ControlSerializer
# ---------------------------------------------------------------------------
class ControlSerializer(serializers.ModelSerializer):
    risks = serializers.PrimaryKeyRelatedField(many=True, queryset=Risk.objects.all())

    class Meta:
        model = Control
        fields = [
            "id",
            "title",
            "status",
            "created_at",
            "updated_at",
            "due_date",
            "responsible",
            "description",
            "wiki_link",
            "risks",
        ]


# ---------------------------------------------------------------------------
# RiskSerializer
# ---------------------------------------------------------------------------
class RiskSerializer(serializers.ModelSerializer):
    # Nested representation of related controls (read-only)
    controls = ControlSerializer(many=True, read_only=True)

    class Meta:
        model = Risk
        fields = [
            "id",
            "title",
            "asset",
            "process",
            "category",
            "created_at",
            "updated_at",
            "likelihood",
            "impact",
            "score",
            "level",
            "status",
            "owner",
            "follow_up",
            "cia",
            "controls",
        ]


# ---------------------------------------------------------------------------
# AuditSerializer
# ---------------------------------------------------------------------------
class AuditSerializer(serializers.ModelSerializer):
    class Meta:
        model = AuditLog
        fields = [
            "id",
            "user",
            "action",
            "model",
            "object_id",
            "changes",
            "timestamp",
        ]


# ---------------------------------------------------------------------------
# UserSerializer
# ---------------------------------------------------------------------------
User = get_user_model()

class UserSerializer(serializers.ModelSerializer):
    risks_owned = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    controls_responsible = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = User
        fields = [
            "id",
            "username",
            "email",
            "is_sso_user",
            "risks_owned",
            "controls_responsible",
        ]


# ---------------------------------------------------------------------------
# RiskSummarySerializer
# ---------------------------------------------------------------------------
class RiskSummarySerializer(serializers.ModelSerializer):
    class Meta:
        model = Risk
        fields = ["id", "title", "score", "level"]


# ---------------------------------------------------------------------------
# IncidentSerializer
# ---------------------------------------------------------------------------
class IncidentSerializer(serializers.ModelSerializer):
    related_risks = serializers.PrimaryKeyRelatedField(
        many=True, queryset=Risk.objects.all()
    )
    date_reported = serializers.DateField(format="%Y-%m-%d", required=False)
    created_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    updated_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)

    class Meta:
        model = Incident
        fields = [
            "id",
            "title",
            "description",
            "date_reported",
            "created_at",
            "updated_at",
            "status",
            "related_risks",
        ]

    def create(self, validated_data):
        """Ensure related_risks are set after creation."""
        risks = validated_data.pop("related_risks", [])
        obj = super().create(validated_data)
        if risks:
            obj.related_risks.set(risks)
        return obj

    def update(self, instance, validated_data):
        """Ensure related_risks are updated properly."""
        risks = validated_data.pop("related_risks", None)
        obj = super().update(instance, validated_data)
        if risks is not None:
            obj.related_risks.set(risks)
        return obj
