import type { UsersId } from "~/schemas/public/Users";
import { db } from "~/server/db";
import { TRPCError } from "@trpc/server";
import { genMail, type MailsTemplates } from "~/server/services/mailer";

export const StoreEmail = async ({
  userId,
  data,
}: {
  userId: UsersId;
  data: MailsTemplates;
}) => {
  try {
    return await db
      .insertInto("emails")
      .values({
        user_id: userId,
        data,
      })
      .returning("id_email")
      .execute();
  } catch (e) {
    throw new TRPCError({
      code: "INTERNAL_SERVER_ERROR",
      message:
        "Errore durante il salvataggio dell'email: " + (e as Error).message,
    });
  }
};

export const GetEmails = async ({ userId }: { userId: UsersId }) => {
  try {
    const mails = await db
      .selectFrom("emails")
      .selectAll()
      .where("user_id", "=", userId)
      .orderBy("created_at", "desc")
      .execute();

    const gen = await Promise.all(
      mails.map(async (mail) => {
        return {
          ...(await genMail(mail.data as MailsTemplates)),
          created_at: mail.created_at,
        };
      }),
    );

    return gen;
  } catch (e) {
    throw new TRPCError({
      code: "INTERNAL_SERVER_ERROR",
      message:
        "Errore durante il recupero delle email: " + (e as Error).message,
    });
  }
};
