// index.js

import express from 'express';
import fetch from 'node-fetch';
import {simpleParser} from 'mailparser';

const app = express();
const PORT = 3334;

app.get('/', async (req, res) => {
    try {
        const response = await fetch('http://localhost:4566/_aws/ses');
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const data = await response.json();
        const messagesHtml = await parseMessages(data.messages);
        res.send(renderHtml(messagesHtml));
    } catch (error) {
        console.error('Error fetching messages:', error);
        res.status(500).send('Error fetching messages');
    }
});

async function parseMessages(messages) {
    const parsedMessages = await Promise.all(
        messages.map(async (message, index) => {
            try {
                const parsed = await simpleParser(message.RawData);
                return `
                    <div class="shadow-md rounded-lg p-4 mb-6" style="background-color: lightgray">
                     <div class="shadow-md rounded-lg p-4 mb-6" style="background-color: white">
                        <div class="mb-2">
                            <span class="font-bold text-lg">Message ${index + 1}</span>
                        </div>
                        <div class="mb-2">
                            <span class="font-semibold">From:</span> ${message.Source}
                        </div>
                        <div class="mb-2">
                            <span class="font-semibold">Region:</span> ${message.Region}
                        </div>
                        <div class="mb-2">
                            <span class="font-semibold">Timestamp:</span> ${message.Timestamp}
                        </div>
                     </div>
                        <div class="prose">
                            ${parsed.html || parsed.textAsHtml || 'No HTML content available'}
                        </div>
                    </div>
                `;
            } catch (error) {
                console.error('Error parsing email:', error);
                return `
                    <div class="bg-white shadow-md rounded-lg p-4 mb-6">
                        <div class="mb-2">
                            <span class="font-bold text-lg">Message ${index + 1}</span>
                        </div>
                        <div class="mb-2">
                            <span class="font-semibold">From:</span> ${message.Source}
                        </div>
                        <div class="mb-2">
                            <span class="font-semibold">Region:</span> ${message.Region}
                        </div>
                        <div class="mb-2">
                            <span class="font-semibold">Timestamp:</span> ${message.Timestamp}
                        </div>
                        <div class="text-red-500">
                            Error parsing email content
                        </div>
                    </div>
                `;
            }
        })
    );
    return parsedMessages.join('');
}

function renderHtml(messagesHtml) {
    return `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Email Messages Viewer</title>
            <script src="https://cdn.tailwindcss.com"></script>
            <style>
                body {
                    background-color: #f3f4f6;
                    font-family: Arial, sans-serif;
                }
                .container {
                    max-width: 800px;
                    margin: 50px auto;
                    padding: 20px;
                }
                .prose {
                    line-height: 1.6;
                }
            </style>
        </head>
        <body>
            <div class="container bg-white shadow-lg rounded-lg p-6">
                <h1 class="text-2xl font-bold text-center mb-6">Email Messages Viewer</h1>
                <div id="messages-container">
                    ${messagesHtml}
                </div>
            </div>
        </body>
        </html>
    `;
}

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});