"""
Invoice PDF views
API endpoints for generating and downloading invoice PDFs
"""
from django.http import HttpResponse
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from igny8_core.business.billing.models import Invoice
from igny8_core.business.billing.services.pdf_service import InvoicePDFGenerator
from igny8_core.business.billing.utils.errors import not_found_response
import logging

logger = logging.getLogger(__name__)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def download_invoice_pdf(request, invoice_id):
    """
    Download invoice as PDF
    
    GET /api/v1/billing/invoices/<id>/pdf/
    """
    try:
        invoice = Invoice.objects.prefetch_related('line_items').get(
            id=invoice_id,
            account=request.user.account
        )
    except Invoice.DoesNotExist:
        return not_found_response('Invoice', invoice_id)
    
    # Generate PDF
    pdf_buffer = InvoicePDFGenerator.generate_invoice_pdf(invoice)
    
    # Return PDF response
    response = HttpResponse(pdf_buffer.read(), content_type='application/pdf')
    response['Content-Disposition'] = f'attachment; filename="invoice_{invoice.invoice_number}.pdf"'
    
    logger.info(f'Invoice PDF downloaded: {invoice.invoice_number} by user {request.user.id}')
    
    return response
