"use server";
import axios from "axios";
import ContactFormEmail from "@app/email-templates/ContactTemplate";
import { Resend } from "resend";

export const ApiUrl = async (urlPath: String) => {
  const apiURL = `${process.env.API_URL}/${process.env.API_VERSION}/${urlPath}`;
  return apiURL;
};

interface ParseError {
  path: string[];
  message: string;
}

interface ParseResult {
  error?: {
    issues: ParseError[];
  };
  data?: {
    fullName?: String;
    email?: String;
    businessName?: String;
    phoneNumber?: String;
    description?: String;
    interestField?: String;
  };
}

export async function createContactFormSubmission(
  prevState: {
    message: string;
  },
  formData: any,
  gRecaptchaToken: string
) {
  const secretKey = process.env.RECAPTCHA_SECRET_KEY;

  let res;

  let formDataUrl = `secret=${secretKey}&response=${gRecaptchaToken}`;

  const error_fields: { [key: string]: string } = {};
  let status;
  let message;

  try {
    res = await axios.post(
      "https://www.google.com/recaptcha/api/siteverify",
      formDataUrl,
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      }
    );
  } catch (e) {
    error_fields["recaptcha"] = "Recaptcha Failed";
    status = "error";
    message = "error";

    return { error: error_fields, message, status };
  }

  if (res && res.data?.success && res.data?.score > 0.5) {
    const url = await ApiUrl("contact/request");

    const formDataObject: Record<string, string> = {};
    for (const [key, value] of formData.entries()) {
      formDataObject[key] = value as string;
    }

    const jsonData: string = JSON.stringify(formDataObject);
    let responseData;

    try {
      const res = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: jsonData,
      });

      const data: any = await res.json();
      responseData = data;
    } catch (e) {
      console.log(e);
    }

    if (responseData.errors) {
      status = "error";
      message = "error";
      return { error: responseData.errors, message, status };
    } else {
      message = responseData.data[0].successMessage;
      status = "success";

      if (process.env.ENABLE_RESEND && process.env.ENABLE_RESEND === "TRUE") {
        interface ContactFormProps {
          firstName: string;
          lastName: string;
          phone: string;
          description: string;
        }

        const PreviewProps = {
          firstName: responseData.data[0].firstName,
          lastName: responseData.data[0].lastName,
          phone: responseData.data[0].phone,
          description: responseData.data[0].description,
        } as ContactFormProps;

        const resend = new Resend(`${process.env.RESEND_KEY}`);
        try {
          await resend.emails.send({
            from: "onboarding@resend.dev",
            to: process.env.EMAIL_TO as string,
            subject: `${process.env.APP_NAME} contact`,
            react: ContactFormEmail(PreviewProps),
          });
        } catch (error) {
          console.log(error);
        }
      } else {
        console.log("Email disabled");
      }

      return { error: error_fields, message, status };
    }
  } else {
    error_fields["recaptcha"] = "Recaptcha Failed";
    message = "error";
    status = "error";
    return { error: error_fields, message, status };
  }
}
