import os
from pathlib import Path

import boto3
import pytest
from layercake.dateutils import now
from layercake.email_ import Message, formataddr
from moto import mock_aws


@pytest.fixture(scope='function')
def aws_credentials():
    """Mocked AWS Credentials for moto."""
    os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
    os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing'
    os.environ['AWS_SECURITY_TOKEN'] = 'testing'
    os.environ['AWS_SESSION_TOKEN'] = 'testing'
    os.environ['AWS_DEFAULT_REGION'] = 'sa-east-1'


def test_formataddr():
    assert (
        formataddr(('Sérgio', 'sergio@somosbeta.com.br'))
        == '=?utf-8?q?S=C3=A9rgio?= <sergio@somosbeta.com.br>'
    )

    assert formataddr('sergio@somosbeta.com.br') == 'sergio@somosbeta.com.br'

    assert (
        formataddr(
            [
                ('Sérgio', 'sergio@somosbeta.com.br'),
                ('Tiago', 'tiago@somosbeta.com.br'),
            ]
        )
        == '=?utf-8?q?S=C3=A9rgio?= <sergio@somosbeta.com.br>, Tiago <tiago@somosbeta.com.br>'
    )


def test_send_email():
    from_ = ('EDUSEG®', 'pytest@eduseg.com.br')
    to = [
        ('Sérgio', 'sergio+pytest1@somosbeta.com.br'),
        ('Sergio', 'sergio+pytest2@somosbeta.com.br'),
    ]
    emailmsg = Message(
        to=to,
        from_=from_,
        bcc='osergiosiqueira@gmail.com',
        subject='áéíóúnõ',
        reply_to=('', 'osergiosiqueira@gmail.com'),
        content='<b>Lorem ipsum dolor sit amet, consectetur adipiscing elit</b>',
    )
    emailmsg.add_header('X-Feedback', f'uid=123; oid=123; date={now().isoformat()}')
    emailmsg.add_alternative(
        """
        <h2>áéíóúnõ</h2>
        html
        """
    )
    emailmsg.attach(Path('tests/samples/test.pdf'), 'relatório.pdf')

    with mock_aws():
        ses = boto3.client('ses', region_name='sa-east-1')
        ses.verify_email_identity(EmailAddress=from_[1])

        sesv2 = boto3.client('sesv2')
        r = sesv2.send_email(
            Content={
                'Raw': {
                    'Data': emailmsg.as_bytes(),
                },
            }
        )

        assert 'MessageId' in r
