# =============================================================
# invoices/views.py — Rēķinu API ViewSet (DROŠĪBA SALABOTA)
# =============================================================

from rest_framework import viewsets, permissions
from rest_framework.decorators import api_view, permission_classes as perm_classes
from .models import Rekkins
from .serializers import RekkinsSerializer
from .utils import render_to_pdf
from django.http import HttpResponse

class RekkinsViewSet(viewsets.ReadOnlyModelViewSet):
    """
    Rēķinu saraksts un detaļas.
    ReadOnly — rēķinus izveido tikai Admin caur /admin paneli.

    RBAC:
    - Admin / is_staff  → redz VISUS rēķinus
    - Klients           → redz tikai SAVUS rēķinus
    """
    serializer_class   = RekkinsSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user

        # Admins redz visu
        if user.is_staff or getattr(user, 'role', '') in ('admin', 'superadmin'):
            return Rekkins.objects.select_related('klients', 'projekts').all()

        # Klients redz tikai savus
        return Rekkins.objects.select_related(
            'klients', 'projekts'
        ).filter(klients=user)


# === DROŠĪBA (CRIT-04): PDF ar autentifikāciju un autorizāciju ===
@api_view(['GET'])
@perm_classes([permissions.IsAuthenticated])
def download_invoice_pdf(request, invoice_id):
    """
    Drošs PDF lejupielādes endpoint.
    - Tikai autentificēti lietotāji
    - Klients var lejupielādēt tikai SAVUS rēķinus
    - Admins var lejupielādēt visus
    """
    try:
        invoice = Rekkins.objects.get(id=invoice_id)
    except Rekkins.DoesNotExist:
        return HttpResponse("Rēķins nav atrasts", status=404)

    # === AUTORIZĀCIJA: pārbaudām, vai lietotājam ir tiesības ===
    user = request.user
    if not user.is_staff and invoice.klients != user:
        return HttpResponse("Nav atļaujas skatīt šo rēķinu.", status=403)

    # Sagatavojam datus veidnei
    data = {
        'numurs': invoice.numurs,
        'klients': invoice.klients,
        'projekts': invoice.projekts,
        'summa': invoice.summa,
        'apraksts': invoice.apraksts,
        'izrakstits': invoice.izrakstits,
        'termins': invoice.termins,
    }

    # Ģenerējam PDF
    pdf = render_to_pdf('invoices/invoice_pdf.html', data)
    
    if pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        filename = f"Rekins_{invoice.numurs}.pdf"
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        return response
    return HttpResponse("Kļūda ģenerējot PDF", status=500)
