# =============================================================
# invoices/serializers.py — Rēķinu Serializators
# =============================================================

from rest_framework import serializers
from .models import Rekkins


class RekkinsSerializer(serializers.ModelSerializer):

    # ── TULKOŠANA PRIEKŠ REACT ────────────────────────────────
    # React saņems anglisku nosaukumu laukus
    invoice_number = serializers.CharField(source='numurs',    read_only=True)
    description    = serializers.CharField(source='apraksts',  read_only=True)
    amount         = serializers.DecimalField(source='summa',  max_digits=10, decimal_places=2, read_only=True)
    status         = serializers.CharField(source='statuss',   read_only=True)
    issued_date    = serializers.DateField(source='izrakstits', read_only=True)
    due_date       = serializers.DateField(source='termins',   read_only=True, allow_null=True)
    paid_date      = serializers.DateField(source='apmaksats_datums', read_only=True, allow_null=True)

    # Klienta vārds
    client_name = serializers.SerializerMethodField()

    # Projekta nosaukums (ja piesaistīts)
    project_name = serializers.SerializerMethodField()

    class Meta:
        model = Rekkins
        fields = [
            'id',
            'invoice_number',
            'client_name',
            'project_name',
            'description',
            'amount',
            'status',
            'issued_date',
            'due_date',
            'paid_date',
        ]

    def get_client_name(self, obj):
        if obj.klients:
            return getattr(obj.klients, 'full_name', obj.klients.email)
        return '—'

    def get_project_name(self, obj):
        if obj.projekts:
            return obj.projekts.nosaukums
        return '—'
