from datetime import date, datetime, timedelta
from django.template.response import TemplateResponse
from alkatorapi.models import User
from weasyprint import HTML
from pypdf import PdfWriter
import asyncio

def html_to_pdf(html_content, output_path):
    HTML(string=html_content).write_pdf(output_path)

merger = PdfWriter()

for user in User.objects.all().order_by('last_name', 'first_name'):
    template = TemplateResponse(
        None,
        'invoice.html',
        {
            'user': user,
            'paid_date': user.register_date + timedelta(days=1),
        }
    )
    template.render()
    pdf_name = f"{user.last_name}_{user.first_name}.pdf"
    html_to_pdf(template.content, pdf_name)
    merger.append(pdf_name)

merger.write('result.pdf')
merger.close()
