import Mailjet from 'node-mailjet';

export default defineEventHandler(async (event) => {
    
    // Handle request
    const body = await readBody(event);

    // Instantiate and setup Mailjet
    const mailjet = new Mailjet({
        apiKey: useRuntimeConfig().mailjetApiPublic,
        apiSecret: useRuntimeConfig().mailjetApiPrivate
    });

    // Send email
    try {
        const response = await mailjet
            .post('send', { version: 'v3.1' })
            .request({
                Messages: [
                    {
                        From: {
                            Email: 'contact@paulnicoue.com',
                            Name: body.name,
                        },
                        To: [
                            {
                                Email: 'contact@paulnicoue.com',
                                Name: 'Paul Nicoué',
                            },
                        ],
                        Subject: body.subject,
                        HTMLPart:
                            `<div><b>Nom :</b> ${body.name}</div>
                            <div><b>Adresse e-mail :</b> <a href="mailto:${body.email}" target="_blank">${body.email}</a></div>
                            <br />
                            <div>${body.message}</div>`
                    }
                ]
            });
        console.log(response.body);
    } catch (error) {
        console.log(error.statusCode);
    } finally {
        // End response without providing data
        event.node.res.end();
    }

});
