import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { Resend } from 'resend';
const resend = new Resend('re_xxxxxxxxx');
export const POST = async (request: NextRequest) => {
  const event = await request.json();
  if (event.type === 'email.received') {
    const { data: email } = await resend
      .emails
      .receiving
      .get(event.data.email_id);
    const { data: attachments } = await resend
      .attachments
      .receiving
      .list({ emailId: event.data.email_id });
    // download the attachments and encode them in base64
    for (const attachment of attachments.data) {
      const response = await fetch(attachment.download_url);
      const buffer = Buffer.from(await response.arrayBuffer());
      attachment.content = buffer.toString('base64');
    }
    const { data, error } = await resend.emails.send({
      from: 'Acme <onboarding@resend.dev>',
      to: ['delivered@resend.dev'],
      subject: event.data.subject,
      html: email.html,
      text: email.text,
      attachments
    });
    return NextResponse.json(data);
  }
  return NextResponse.json({});
};