import { sendEmail } from "@/utils/email";
import { getOneMessage, newMessage, replyToMessage } from "@/utils/message";
import { ActionError, defineAction } from "astro:actions";
import { z } from "astro:schema";

// The JWT secret
const secret = new TextEncoder().encode(import.meta.env.SESSION_SECRET);
export const sendMessage = defineAction({
  accept: "form",
  input: z.object({
    email: z.string().email(),
    name: z.string(),
    subject: z.string(),
    message: z.string(),
  }),
  handler: async ({ name, email, subject, message }) => {
    // checks for email + password combinaison
    const [chat, mail] = await Promise.all([
      newMessage({
        name,
        email,
        subject,
        message,
      }),
      sendEmail({
        from: email,
        subject,
        text: message,
        to: "info@sambekiel.com",
      }),
    ]);
    if (!chat || !mail) {
      // if email or password incorrect, flash a message to show the user what is the error
      throw new ActionError({
        code: "INTERNAL_SERVER_ERROR",
        message: "Error Occured While Submitting",
      });
    }

    // return a successful response
    return {
      message: "Message Sent Successfully",
    };
  },
});
export const replyMessage = defineAction({
  accept: "form",
  input: z.object({
    email: z.string().email(),
    name: z.string(),
    subject: z.string(),
    message: z.string(),
    chat_id: z.number(),
  }),
  handler: async ({ message, chat_id }, ctx) => {
    const dbChat = await getOneMessage(Number(chat_id));

    if (!dbChat) {
      throw new ActionError({
        code: "NOT_FOUND",
        message: "You can not reply a non-existing message",
      });
    }

    const [chat, mail] = await Promise.all([
      replyToMessage({
        message,
        chatId: chat_id,
        // @ts-ignore
        repliedBy: ctx.locals.user.id,
      }),
      sendEmail({
        to: dbChat?.chat?.email!,
        subject: `Re: ${dbChat?.chat?.subject!}`,
        text: message,
        from: "info@sambekiel.com",
      }),
    ]);
    if (!chat || !mail) {
      // if email or password incorrect, flash a message to show the user what is the error
      throw new ActionError({
        code: "INTERNAL_SERVER_ERROR",
        message: "Error Occured While Submitting",
      });
    }

    // return a successful response
    return {
      message: "Message Sent Successfully",
    };
  },
});
