"use server"
import { Resend } from "resend"
import { validateString } from "@/lib/utils";
import OrderFormEmailClient from "../emailTemplates/order-form-email-client";
import React from "react";
import 'dotenv/config';

const resend = new Resend(process.env.RESEND_API_KEY);

export const sendEmail = async (formData: FormData) => {
    //rate limit

    //only allow authenticated user as well

    const senderEmail = formData.get('senderEmail');
    const order = formData.get('order');

    if (!validateString(senderEmail, 500)){
        return{ error: "Invalid sender Email",};
    }
    if (!validateString(order, 5000)){
        return{ error: "Invalid message",};
    }

    // console.log("Running on sever");
    // console.log(formData.get("senderEmail"));
    // console.log(formData.get("message"));

    try {
        await resend.emails.send({
            from:"Kevos Official <orders@kevosattire.com>",
            // to:"arcjcb11@gmail.com",
            to: senderEmail as string,
            subject: "New Order",
            // reply_to: senderEmail as string,
            // text: message as string,
            react: React.createElement(OrderFormEmailClient, {order: order as string, senderEmail: senderEmail as string}),
        });
    } catch (error: unknown){
        return console.log(error)
    }
};