import { TRPCError } from "@trpc/server";
import type { EmailsIdEmail } from "~/schemas/public/Emails";
import type { UsersId } from "~/schemas/public/Users";
import { db } from "~/server/db";
import type { MailsTemplates } from "~/server/services/mail-templates";
import { genMail } from "~/server/services/mailer";

export const storeEmail = async ({
	userId,
	data,
}: {
	userId: UsersId;
	data: MailsTemplates;
}) => {
	try {
		return await db
			.insertInto("emails")
			.values({
				data,
				user_id: userId,
			})
			.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,
					id_email: mail.id_email,
				};
			}),
		);

		const obsoleteMails = gen.filter((mail) => mail.html === "");

		if (obsoleteMails.length > 0) {
			await db
				.deleteFrom("emails")
				.where(
					"id_email",
					"in",
					obsoleteMails.map((mail) => mail.id_email),
				)
				.execute();
		}

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

export const deleteEmail = async ({
	id_email,
}: {
	id_email: EmailsIdEmail;
}) => {
	try {
		await db.deleteFrom("emails").where("id_email", "=", id_email).execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore durante l'eliminazione dell'email: ${(e as Error).message}`,
		});
	}
};

export const deleteAllUserEmails = async ({ userId }: { userId: UsersId }) => {
	try {
		await db.deleteFrom("emails").where("user_id", "=", userId).execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore durante l'eliminazione delle email dell'utente: ${(e as Error).message}`,
		});
	}
};
