import nodemailer from "nodemailer";
import { createId } from "@paralleldrive/cuid2";
import { InfisicalClient } from "@infisical/sdk";

const client = new InfisicalClient({
  siteUrl: import.meta.env.INFISICAL_URL,
  auth: {
    universalAuth: {
      clientId: import.meta.env.INFISICAL_CLIENTID,
      clientSecret: import.meta.env.INFISICAL_SECRET,
    },
  },
});

export const POST = async ({ request }) => {
  try {
    var secrets = await client.listSecrets({
      environment: "dev",
      projectId: import.meta.env.INFISICAL_PROJECTID,
      path: "/email",
      includeImports: false,
    });
    secrets = Object.fromEntries(
      secrets.map((item) => [item.secretKey, item.secretValue])
    );
    const thisCuid = createId();
    const data = await request.formData();
    var message = {
      from: `${data.get("username")} <${secrets["EMAIL"]}>`,
      to: `Site Admin <${secrets["RECEIVER"]}>`,
      subject: `${secrets["EMAIL_HEAD"]} | ${thisCuid}`,
      text: `---\n${data.get("username")}\n${data.get(
        "email"
      )}\n---\n${data.get("message")}`,
      html: `<p>---<br/>${data.get("username")}<br/>${data.get(
        "email"
      )}<br/>---<br/>${data.get("message")}</p>`,
      envelope: {
        from: `${data.get("username")} <${secrets["EMAIL"]}>`,
        to: `Site Admin <${secrets["RECEIVER"]}>`,
      },
    };
    var transport = nodemailer.createTransport({
      host: secrets["SMTP_SERVER"],
      port: secrets["SMTP_PORT"],
      secure: secrets["SMTP_SECURITY"],
      auth: {
        user: secrets["EMAIL"],
        pass: secrets["PASSWORD"],
      },
    });

    var mailResponse = await transport.sendMail(message);
    return new Response(JSON.stringify({ message: "Success!" }), {
      status: 200,
    });
  } catch (error) {
    console.error("Error parsing form data:", error);
    return new Response(
      JSON.stringify({ message: "Failed to parse form data" }),
      { status: 400 }
    );
  }
};