<gh_stars>1-10
from httpx import AsyncClient, BasicAuth
from typing import List
from uuid import UUID

from app.connectors.mailgun.models import InvitasjonUploadUrl, InvitasjonEmail


class MailgunClient:
    def __init__(self, domain: str, secret: str, tusd_url: str, testmode: bool = False):
        """Initialize a new MailgunClient"""
        self.url = f'https://api.eu.mailgun.net/v3/{domain}/messages'
        self.secret = secret
        self.domain = domain
        self.tusd_url = tusd_url
        self.testmode = testmode

    async def send_invitasjon(self, to: List[str], arkivuttrekk_obj_id: UUID, arkivuttrekk_tittel: str, invitasjon_ekstern_id: UUID):
        """Send an invitasjon email to a list of recipients"""

        upload_url = InvitasjonUploadUrl(arkivuttrekk_obj_id, self.tusd_url, invitasjon_ekstern_id).as_base64_url()
        email = InvitasjonEmail(self.domain, to, arkivuttrekk_obj_id, arkivuttrekk_tittel, upload_url)

        async with AsyncClient(auth=BasicAuth('api', self.secret)) as client:
            email_data = email.as_data()

            if self.testmode:
                email_data['o:testmode'] = 'true'

            resp = await client.post(self.url, data=email_data)

            return resp
